typestar

Optional chaining in Swift

One ? short-circuits the whole path to nil.

struct Skipper {
    var name: String
    var boat: Boat?
}
struct Boat {
    var name: String
    var sailNumber: Int
}

let rae = Skipper(name: "Rae", boat: Boat(name: "Kestrel", sailNumber: 207))
let visitor = Skipper(name: "Sam", boat: nil)

// Each ? short-circuits the whole chain to nil.
print(rae.boat?.name ?? "no boat")
print(visitor.boat?.name ?? "no boat")

// The chain's type is Optional even at the end.
let sail: Int? = rae.boat?.sailNumber
print("Sail #\(sail ?? 0)")

How it works

  1. rae.boat?.name reads through the optional boat.
  2. A nil anywhere makes the whole chain nil, quietly.
  3. The result stays Optional: let sail: Int?.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
468
Tokens
122
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 113 seconds.

Type this snippet

Step 3 of 3 in Optionals, step 12 of 27 in Language basics.

← Previous Next →