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()
.
class Human {
var name: String
init(name: String) {
self.name = name
}
print("Hello, I'm \(name)")
}
}
Create an instance of Apartment
and assign its human
property.
var seoulApartment = Apartment()
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.
if let name = myName {
print(name)
}
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.