Optionals: Free iOS Development Tutorial

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this iOS Development tutorial:

Declaring & unwrapping optionals, Checking optionals for a nil value, Optional binding, Implicitly unwrapped optionals

Exercise Overview

Not all constants or variables will necessarily have a value. For instance, a location on a map may not have a name that can be displayed on a label. To prevent errors in these situations, you can use optionals—constants or variables that may or may not contain a value. In this exercise, you’ll explore how to use optionals and check for nil (blank) values.

Getting Started

  1. Launch Xcode if it isn’t already open.

  2. Go to File > New > Playground.

  3. Under iOS, double–click on Blank.

  4. Navigate into: Desktop > Class Files > yourname-iOS App Dev 1 Class

  5. Save the file as: Optionals.playground

  6. Click Create.

Declaring & Unwrapping Optionals

With an optional, you can assign a value after it’s been declared. Let’s see how to specify that a constant or variable is optional.

  1. Let’s say that players have the option to have a pet in our game. Not all players will take us up on the offer, so we need to make its variable optional by adding a question mark at the end. Replace the default var str line with the following bold code, making sure to include the question mark (?):

    var playerPet: String?
    
  2. In the results sidebar on the right, notice it says nil. This means the variable has no value. It is important to note because when an app is trying to go into a variable and access data that has a nil value, it can cause the app to crash.

  3. As shown in bold, assign a value to the variable and print the following message:

    var playerPet: String?
    playerPet = "Horse"
    print("You chose a \(playerPet) as your pet")
    
  4. Notice on the right it says: You chose a Optional("Horse") as your pet.

    NOTE: If you don’t see all the text, hover over the vertical divider line to the left of the sidebar. Once you see a resize handle splitter, drag to the left until you see it all.

  5. When using optionals that contain a value, you need to do something called forced unwrapping, which is done by putting an exclamation point (!) after the variable name. This basically says that you know the optional has an assigned value, and that you’d like to use it. Add an exclamation point to the variable, as shown below in bold:

    print("You chose a \(playerPet!) as your pet")
    

    Now it should read: You chose a Horse as your pet

Checking Optionals for a Nil Value

We often need to make sure that a constant or variable has a value before we use it. Let’s see how to do this using if statements.

  1. Let’s say that by default, players barter in our game. If they want to use money instead, they will have to make an in-app purchase. Because not all players will be using money, let’s start off by declaring an optional value for it, as shown in bold:

    print("You chose a \(playerPet!) as your pet")
    
    var playerMoney: Double?
    
  2. Notice in the results sidebar on the right, nil appears because our playerMoney optional is currently nil (like it would be for players using the default barter system).

  3. Let’s assign a value:

    var playerMoney: Double?
    playerMoney = 50.25
    
  4. Add a print function, including an exclamation point to force unwrap the optional:

    playerMoney = 50.25
    print("\(playerMoney!)")
    
  5. Now on the right it should say: 50.25

  6. The reason you would use an optional is in cases where there may or may not be a value. If you try to force unwrap an optional that doesn’t have a value, there will be a problem. To demonstrate this, set playerMoney to nil, as shown in bold:

    playerMoney = nil
    

    IMPORTANT: You can’t assign a nil value to a constant or variable that isn’t optional. This is one of the benefits of using optionals.

  7. There is a red error red alert icon because you’re trying to force unwrap something that does not exist.

  8. What we need to do is check whether or not the value is nil before we attempt to do anything with it. Add the following bold if statement that says if playerMoney does not equal nil (and therefore has a value), then execute the command in parentheses:

    playerMoney = nil
    if playerMoney != nil {
       print("Your player has \(playerMoney!) dollars")
    }
    
  9. Right now it’s not executing anything because playerMoney does equal nil. As shown in bold below, set playerMoney back to 50.25:

    playerMoney = 50.25
    if playerMoney != nil {
    

    Now on the right it says: Your player has 50.25 dollars

Optional Binding

Optional binding is Swift’s built-in way of checking if an optional has a nil value. If there is a value, it unwraps it for you (without you having to use exclamation marks) and places the unwrapped value into a temporary variable or constant.

  1. At the bottom, create a new variable that represents a player’s skill level (which is optional because it can only be determined after the player has completed a level):

    var playerSkillLevel: Int?
    
  2. As shown below in bold, give the variable a value:

    var playerSkillLevel: Int?
    playerSkillLevel = 10
    
  3. At the bottom create an if statement using optional binding:

    playerSkillLevel = 10
    
    if let skillLevel = playerSkillLevel {
       print("\(skillLevel)")
    }
    

    Here you’re saying if playerSkillLevel does not equal nil, assign its value to the constant skillLevel. (!= nil is implicit in this statement.) Then it prints the value of that constant. Because you’ve assigned the optional’s value back to a new, temporary constant or variable, you don’t have to unwrap the results.

    On the right, it says: 10

  4. To see what happens if playerSkillLevel equals nil, comment out the value:

    //playerSkillLevel = 10
    
  5. Notice the value 10 disappears from the sidebar on the right. When your code has an error, nothing will print below the line where the error occurred. To make sure we’re not actually getting an error, add an else statement at the bottom as shown:

    if let skillLevel = playerSkillLevel {
       print("\(skillLevel)")
    } else {
       print("No error")
    }
    
  6. Look in the sidebar to see that it’s working as expected because it says: No error

Implicitly Unwrapped Optionals

Regular optionals are created with a question mark (?) at the end. When you create an optional with an exclamation mark (!) instead, it’s automatically unwrapped when you use it. These are called implicitly unwrapped optionals.

Using implicitly unwrapped optionals can be convenient because you don’t have to unwrap the value every time. However, it’s important to note that you should only use implicitly unwrapped optionals if you know you will definitely be assigning a value before you use them. It’s up to you as a programmer to know when they are appropriate. If there’s a chance that there may be a nil value, you should NOT use implicitly unwrapped optionals because it will cause an error.

  1. Our game will only print out the player’s score once they complete a level. Because it’s impossible to not have a score by this time, we know the value of their score will never be nil. This means it’s safe to declare its variable as an implicitly unwrapped optional. As shown below, create a variable and assign a value to it:

    var playerScore: Int!
    playerScore = 100
    
  2. Add a print function at the bottom:

    playerScore = 100
    print("Your score is \(playerScore)")
    
  3. On the right, notice it says: Your score is Optional(100)

  4. Similar to optionals, if we don’t provide a value when the implicitly unwrapped optional is declared, the value will automatically default to nil. Comment out the value for playerScore as shown below:

    var playerScore: Int!
    //playerScore = 100
    print("Your score is \(playerScore)")
    
  5. On the right, notice it says: Your score is nil

  6. Let’s see what happens if our implicitly unwrapped optional is nil and we try to access its wrapped value. Add the exclamation mark (!) as shown:

    var playerScore: Int!
    //playerScore = 100
    print("Your score is \(playerScore!)")
    

    You will immediately get an error. If there is any chance that your variable will become nil at some point, you should not use an implicitly unwrapped optional in your app as it will crash!

  7. Remove the ! to get rid of the error as shown below:

    //playerScore = 100
    print("Your score is \(playerScore)")
    
  8. Save and close the file. Keep Xcode open, as we’ll use it in the next exercise.

How to Learn iOS & Web Development

Master iOS development, web development, coding, and more with hands-on training. iOS development involves designing apps for Apple mobile devices with tools like Xcode and SwiftUI.

Yelp Facebook LinkedIn YouTube Twitter Instagram