Optional Chaining in Swift
If you have studied about swift, you might already saw those weird tailing question mark(?) and that’s an optional.

so, What is an optional?
Optional is a really powerful feature of Swift and the most confusing. but using optional, you can easily check whether a variable or constants has a value or not. You can simply think Optional as a Box. it might has a value in it, or not until you open it(or “unwrap”).

Type safety is a cornerstone of the Swift. That’s why in Swift, variables and constants need to be initialized before they can be accessed.
so there’s several ways to opening the box
- Forced unwrapping

if you try to unwrap the “carName” which is nil(none), you can use “!” to open the “carName” in forced wether carName has a value or not.

Thankfully if carName has a value, then it won’t occurs an error! but what if carName doesn’t have a value(nil)? probably your app will be experiencing a nasty crash.
2. Optional Binding (if let)

to bind the wrapped value of an Optional instance to a new variable, you can use either of if let or guard let.
so for the first example, if unwrappedCarname has a value, then it will print the value otherwise, it will print “Nil”
however for the second example, it will print “cannot be converted to Integer”. because String cannot be converted integer.
3. Optional Binding (guard)

for the “guard let” optional binding works exactly same as “if let” Optional binding except for when the value is nil, then it will return right away.
so what’s the difference between using if let and guard let?
it’s complexity of the code(Cyclomatic Complexity). if you are interested to make the code simple, and be understandable to everyone, try to search about “Cyclomatic Complexity”. (so some people prefer to use guard let)
4. Nil-Coalescing Operator
use the nil-coalescing operator (??) to supply a default value in case the Optional instance is nil.

so if carName has no value(nil), then myCarName will be having a value of “Mercedes”
Optional Chaining
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. “Optional chaining using ?. to call an object either returns value else return nil”. This prevents crashes at runtime and helps you write more productive code.
Accessing properties Through Optional Chaining
can use optional chaining to access a property on an optional value, and to check if that property access is successful.
