Note: Learn Swift with Bob is available on Udemy. If you wish to receive a 30% discount link, you may use the coupon link here.

Optionals

Introduction

Welcome to the first lesson of The Swift Fundamentals. When I first started programming in Swift, I took courses from Udemy, Treehouse, Lynda, and many more. Yet, I could not understand what those ?s and !s stood for. Xcode kept telling me what to do on the left side, causing more problems. It seemed like no instructor could explain the reasoning behind how to use optionals, and most importantly, why Swift engineers have implemented a such feature that is unique compared to other programming languages. Today, You will discover the why with me.

Problem

Why did Swift engineers implement optionals?

Implicit and Explicit Type

Rules

  1. Every variable type must be defined (Implicit/Explicit)
  2. The type is inferred based on the value
  1. // String
  2. let name: String = "Bob" // Explicit
  3. let newName = "Bob the Developer" // Implicit
  4. // Numbers
  5. let myAge: Int = 20 // Explicit
  6. let mySisterAge = 14 // Implicit
  7. let myGPA: Double = 3.54 // Explicit

Reasons for the rules above Google Slide

Fetching Profile Picture

When you fetch a profile picture from Facebook, it may return no value, a.k.anil. However, you may not store nil to a normal type based on the rule above.

  1. // If could return "URL" or "nothing"
  2. // Successful
  3. let myProfileImageURL: String = "https//facebook.com/bobthedeveloper"
  4. // Error
  5. let myProfilePictureURL: String = nil

Introduction to Optionals

Optionals allow storing nil, a.k.a absence of value.

  1. let myName: String? = nil
  2. let yourName: String? = "Bob Lee"
  3. print(myName) // nil
  4. print(yourName) // Optional("Bob Lee")
  5. let bobAge: Int? = nil
  6. let robAge: Int? = 123
  7. let danAge: Int? = 3

Optionals Rules

  1. Optionals/Normal Types do not interact with each other
  2. Convert Optionals to Normal Types for usage. The process is also known as unwrapping.
  1. robAge + danAge
  2. // Error

Optionals Unwrapping

There are two ways to convert/unwrap optional types to normal types

  1. Forced unwrapping
  2. Implicit unwrapping

Forced Unwrapping

You may convert by inserting ! at the end of the variable. Forced Unwrapping should be avoided since it causes a crash if the optional type contains nil since a normal type can’t store nil.

  1. let profileImageFromFacebook: String? = "ImageURL..."
  2. print(profileImageFromFacebook) // Optional

Now, let us unwrap profileImageFromFacebook.

  1. var image = profileImageFromFacebook! // String? converted to String
  2. print(image) // Normal Type
  3. print(profileImageFromFacebook!) // Normal Type

You must unwrap to work with variables.

  1. let newRobAge = robAge!
  2. let newDanAge = danAge!
  3. newRobAge + newDanAge // Good

Bad things happen when you try to force unwrap an optional type whose value contains nil.

  1. var image: String? = nil
  2. let normalImage = image! // let normalImage = nil
  3. // Error

You can’t store nil to a normal type in Swift. It violates the Swift rule.

Implicit Unwrapping

Implicit unwrapping is a safe way to convert. If the optional type contains nil, it does not break the system. Instead, it ignores. Implicit unwrapping is an added feature to an else-if statement.

  1. let imageFromFaceBook: String? = "Bob's Face"
  2. if let normalImage = imageFromFaceBook {
  3. print(normalImage)
  4. } else {
  5. print("There is no image")
  6. }

Now normalImage contains a normal type of String. You may use the normalImage constant within the if block. On the contrary, if imageFromFaceBook contains nil, Swift executes the else block instead.

Source Code

1001_optionals.playground

Resources {#google_slide}

Conclusion

You’ve learned two fundamental concepts in the Swift Programming Language. The rule number one states, every type, even if optionals, has to be defined explicitly or implicitly. Second, there are two ways to unwrap optionals to normal types. You may force unwrap with ! or safety unwrap with if-let.

In the next lesson, you will learn why ? and ! automatically appear when you create an object and access its properties and methods.