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
- A dictionary lookup returns
Int?— the key might be absent. ?? 0supplies the default for the nil case.radioCall?.countchains past nil instead of crashing.
Keywords and builtins used here
IntStringcountletprint
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.
Step 1 of 3 in Optionals, step 10 of 27 in Language basics.