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 nil2 var street: String?3}4 5class Person {6 var name: String // address is optional too and starts as nil7 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 nil12 if let street = person?.address?.street { // person! is safe here because the chain succeeded13 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 address20p1.address = Address()// Optional chaining also works for assignment21p1.address?.street = "Main St"22 // Bob never gets an address23let p2 = Person(name: "Bob")24 // Prints Alice lives at Main St25printStreet(p1)// address is nil: prints No street info for Bob26printStreet(p2)// No person: prints No street info for unknown27printStreet(nil)Output
Alice lives at Main St No street info for Bob No street info for unknown
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