0Pricing
Swift Academy · Lesson

Optional Pattern in switch and for

Match optionals with case let patterns.

Optionals in switch

You can switch directly on an optional. The cases .some(value) and .none match a present value or nil.

let value: Int? = 7
switch value {
case .some(let n):
    print("Got \(n)")
case .none:
    print("Nothing")
}

The ? Shorthand Pattern

Writing case let x? is shorthand for .some(x). The trailing ? means "unwrap into x".

let value: String? = "Swift"
switch value {
case let text?:
    print(text.uppercased())
case nil:
    print("none")
}

All lessons in this course

  1. if let and Shorthand Binding
  2. guard let for Early Exit
  3. Binding Multiple Optionals
  4. Optional Pattern in switch and for
← Back to Swift Academy