Optional Chaining in Swift

Level 3170 keystrokes

Person has an optional address. person.address?.city reads the city only if an address exists, and ?? supplies a default otherwise. Here the address is set, so it prints Tokyo.

Swift code

// Address holds a non-optional city
1struct Address {
2 var city: String
3}
// Person's address may be nil (Address?)
4struct Person {
5 var address: Address?
6}
7
// Creates a person whose address is set
8let person = Person(address: Address(city: "Tokyo"))
// ?. gives a String? (nil if address is nil); ?? falls back to "Unknown". Prints Tokyo
9print(person.address?.city ?? "Unknown")

Output

Tokyo
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.

  • :× 4
  • ?× 4
  • "× 4
  • (× 3
  • )× 3
  • .× 2
  • {× 2
  • }× 2
  • =× 1

More Swift examples at level 3

← Swift typing practice