Optionals Chainings

    However, you might have wondered why ? and ! automatically appear when you access properties and methods of an object. If you haven’t, that’s okay. The goal is to prevent you from guessing. Let us find out what goes under the hood

    Problem

    Why do I see ? and ! when accessing methods and properties?

    You might have seen,

    The mysterious ? appears all of a sudden. Let us attempt to replicate the phenomenon.

    Design Human

    Create a class, Human, which contains a String property, name and a method, sayHello().

    1. class Human {
    2. var name: String
    3. init(name: String) {
    4. self.name = name
    5. }
    6. print("Hello, I'm \(name)")
    7. }
    8. }

    Create an instance of Apartment and assign its human property.

    1. var seoulApartment = Apartment()
    2. seoulApartment.human = Human(name: "Bobby")

    Now, try to grab the human property of seoulApartment. Since the type of human is optional, ? gets added automatically.

    myName is an optional type. Therefore, unwrapping is needed.

    1. if let name = myName {
    2. print(name)
    3. }

    1002_optional_chainings.playground

    My Favorite Xcode Shortcuts , Part 2,

    Conclusion

    You’ve learned optional chaingins provide shortcuts to nested properties and methods among classes and structs. However, ? automatically appears when you access a property whose type is optional to indicate that anything that comes after may contain no value since the optional property may be nil.

    In the next lesson, you will learn how to use a guard statement to implicitly unwrap multiple instead of classic if let statements.

    Again, if you wish to increase your coding productivity, feel free to check my articles posted.