๐ŸŽ“ A1Learner
๐Ÿ”

Swift Unwrapping Optionals

Unwrapping is opening an optional to reach the plain value inside it. Safe unwrapping checks for nil first.

if let opens a held value

The optional holds 88. The if let block runs and prints the plain number.

let score: Int? = 88
if let scoreValue = score {
    print(scoreValue)
} else {
    print("No score")
}

The else branch handles nil

The optional holds nil this time. The else branch runs instead.

let score: Int? = nil
if let scoreValue = score {
    print(scoreValue)
} else {
    print("No score")
}

The same-name shorthand

Writing if let num reuses the name num inside the block. The block prints the plain value 7.

let num: Int? = 7
if let num {
    print(num)
}

guard let leaves early on nil

The function unwraps its input with guard let. A nil input prints Missing and returns at once.

func show(_ value: Int?) {
    guard let v = value else {
        print("Missing")
        return
    }
    print(v)
}
show(3)
show(nil)

Force unwrap on a known value

This optional is known to hold 200. The force unwrap prints the plain number.

let code: Int? = 200
print(code!)

Example

func describe(_ text: String?) {
    guard let text = text else {
        print("No text")
        return
    }
    print(text)
}
let parsed = Int("15")
if let parsed {
    print(parsed)
}
describe("Swift")
describe(nil)

Key points

  • An if let line unwraps an optional only when it holds a value.
  • The else branch of if let runs when the optional holds nil.
  • Writing if let with the same name reuses that name for the unwrapped value.
  • A guard let line unwraps at the top of a function and leaves early on nil.
  • A force unwrap with ! takes the value out without a check.
  • Using ! on an optional that holds nil stops the program with an error.

In this example, the function describe takes an optional string. Its guard let line prints No text and returns when the input is nil, and otherwise prints the unwrapped text. The parsed value comes from the text 15, so the if let block prints the plain number 15. The call with Swift prints Swift. The call with nil prints No text.

Note

Inside an if let block, the unwrapped name is a plain value, not an optional.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

What does an if let block receive when the optional holds a value?