Optional Chaining in Swift

Level 5495 keystrokes

person?.address?.street stops and gives nil as soon as any link is nil. Alice has a street, Bob has no address, and nil has no person at all, so the three calls print different messages.

Swift code

1class Address {
// street is optional and starts as nil
2 var street: String?
3}
4
5class Person {
6 var name: String
// address is optional too and starts as nil
7 var address: Address?
8 init(name: String) { self.name = name }
9}
10
// The parameter itself is optional (Person?)
11func printStreet(_ person: Person?) {
// Three optional links: if any is nil, the whole chain is nil
12 if let street = person?.address?.street {
// person! is safe here because the chain succeeded
13 print("\(person!.name) lives at \(street)")
14 } else {
// person may be nil here, so ?? supplies "unknown"
15 print("No street info for \(person?.name ?? "unknown")")
16 }
17}
18
19let p1 = Person(name: "Alice")
// Gives Alice an empty address
20p1.address = Address()
// Optional chaining also works for assignment
21p1.address?.street = "Main St"
22
// Bob never gets an address
23let p2 = Person(name: "Bob")
24
// Prints Alice lives at Main St
25printStreet(p1)
// address is nil: prints No street info for Bob
26printStreet(p2)
// No person: prints No street info for unknown
27printStreet(nil)

Output

Alice lives at Main St
No street info for Bob
No street info for unknown
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • (× 13
  • )× 13
  • "× 12
  • ?× 9
  • .× 8
  • :× 7
  • {× 6
  • }× 6
  • =× 6
  • \× 3

More Swift examples at level 5

← Swift typing practice