Niko Adrianus Yuwono
Niko Adrianus Yuwono

Reputation: 11112

How to know where Optional Chaining is breaking?

So in iOS Swift we can do optional chaining to simplify the nil checking like in the official documentation

let johnsAddress = Address()
johnsAddress.buildingName = "The Larches"
johnsAddress.street = "Laurel Street"
john.residence!.address = johnsAddress
if let johnsStreet = john.residence?.address?.street {
    println("John's street name is \(johnsStreet).")
} else {
    println("Unable to retrieve the address.")
}
// prints "John's street name is Laurel Street."

I understand about the usage of the optional chaining in john.residence?.address?.street but how can we know where is actually the chain is breaking (if either residence or address is nil). Can we determine if residence or address is nil, or we need to check it again with if-else?

Upvotes: 7

Views: 490

Answers (3)

Kirsteins
Kirsteins

Reputation: 27335

There is no way to tell where optional chaining stopped. However you can use:

if let johnsStreet = john.residence?.address?.street {
    println("John's street name is \(johnsStreet).")
} else if let johnAddress = john.residence?.address {
    println("Unable to retreive street, but John's address is \(johnAddress).")
} else {
    println("Unable to retrieve the address.")
} 

Upvotes: 2

Amadan
Amadan

Reputation: 198324

Don't do the chain then. The chain is only interesting if you don't intend to stop. If you do, break it up at interesting spots - otherwise, where would you put in the code for the bad cases?

if let residence = john.residence {
  if let address = residence.address {
    ...
  } else {
    println("missing address")
  }
} else {
  println("missing residence")
}

Upvotes: 8

Thilo
Thilo

Reputation: 262504

I don't think so. Optional chaining is a convenient shortcut syntax and you are giving up a bit of control along with a couple of keypresses.

If you really need to know where exactly the chain breaks, you have to go link by link into multiple variables.

Upvotes: 5

Related Questions