How to find out where the extra chain is broken?

So, in iOS Swift, we can make an optional chain to simplify the nil check, as 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 street name is \(johnsStreet).") } else { println("Unable to retrieve the address.") } // prints "John street name is Laurel Street." 

I understand the use of an optional chain in john.residence?.address?.street , but how do I know where the chain actually breaks (if either residence or address is nil ). Can we determine if there is residence or address nil , or should we check it again with if-else ?

+7
swift optional
source share
3 answers

Then do not chain. The chain is interesting only if you are not going to stop. If you do, divide it into interesting places - otherwise, where would you enter the code for bad deeds?

 if let residence = john.residence { if let address = residence.address { ... } else { println("missing address") } } else { println("missing residence") } 
+8
source share

I do not think so. Optional chaining is a convenient shortcut syntax, and you give up control of a few keystrokes.

If you really need to know where exactly the chain breaks, you need to follow the link to several variables.

+5
source share

It is not possible to determine where the additional chain is stopped. However, you can use:

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

All Articles