typestar

Optionals in Swift

The maybe-missing value, spelled into the type.

let berths = ["Kestrel": 12, "Sable": 4]

// A dictionary lookup is Optional: the key might not be there.
let kestrelBerth: Int? = berths["Kestrel"]
let ghostBerth: Int? = berths["Osprey"]

// ?? supplies a default; optional chaining stops at nil.
print("Kestrel moors at \(kestrelBerth ?? 0)")
print("Osprey moors at \(ghostBerth ?? 0)")

let radioCall: String? = "Kestrel, Kestrel, race control"
print("Call length: \(radioCall?.count ?? 0)")

How it works

  1. A dictionary lookup returns Int? — the key might be absent.
  2. ?? 0 supplies the default for the nil case.
  3. radioCall?.count chains past nil instead of crashing.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
444
Tokens
92
Three-star pace
70 tpm

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

Type this snippet

Step 1 of 3 in Optionals, step 10 of 27 in Language basics.

← Previous Next →

Optionals in other languages