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
?
How does Optional Chaining work in Javascript? Optional chaining is a feature in Javascript which lets us access child properties of an object, even if the parent object doesn’t exist. It’s used when properties are optional on an object, so that instead of returning an error, we still get a result from Javascript.
The optional chaining operator ( ?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.
Optional chaining cannot be used on a non-declared root object, but can be used with an undefined root object. The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null .
Therefore, treating an evaluated optional chaining expression as a function, object, number, etc., can cause TypeError or unexpected results. For example: Also, parentheses limit the scope of short-circuiting in chains. For example: This rule aims to detect some cases where the use of optional chaining doesn’t prevent runtime errors.
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")
}
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.
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.")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With