Optionals Chainings

Introduction

Welcome to Lesson 2 of The Swift Fundamentals. In the previous lesson, you’ve learned why we use optionals and how to convert them to normal types.

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?

Optional Chaining in UIKit

You might have seen,

  1. import UIKit
  2. let label = UILabel().highlightedTextColor?.cgColor

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. func sayHello() {
  7. print("Hello, I'm \(name)")
  8. }
  9. }

Design Apartment

Create a class, Apartment, which contains a property whose type is Human?.

  1. class Apartment {
  2. var human: Human?
  3. }

Initialize Property

Create an instance of Apartment and assign its human property.

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

Call Property and Method

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

Rules: When you access a property whose type is optional, Swift will add ?. Anything that comes after the ? will be optional.

  1. var myName = seoulApartment.human?.name // Always return an `optional` type since human is `optional`.

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

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

Force Unwrap

You may force unwrap while optional chaining. However, if the property is not initialized, it will crash.

  1. var NYCApartment = Apartment()
  2. let NYCResident = NYCApartment.human!.name // Error: No value for human

Source Code

1002_optional_chainings.playground

Resources

My Favorite Xcode Shortcuts Part 1, Part 2, Part 3

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 optionals instead of classic if let statements.

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