? And! The difference
You specify optional chaining by placing a question mark ( ?
) after the optional value on which we wish to call a prop Erty, method or subscript if the optional is non- nil
. This was very similar to placing a exclamation mark () after a optional value to force the unwrapping of its !
value. The main difference is this optional chaining fails gracefully when nil
the optional is, whereas forced unwrapping Trigg ERs a runtime error when the optional is nil
.
Query value is optional type
To reflect the fact that optional chaining can being called on a nil
value, the result of an optional chaining Always an optional value,
Specifically, the result of a optional chaining call is of the the same type as the expected return value Optional.
let roomCount = john.residence!.numberOfRooms
// this triggers a runtime error
accessing subscripts Through Optional Chaining
You can use optional chaining to try to retrieve and set a value from a subscript on an optional value, and to check Wheth Er that subscript call is successful.
accessing subscripts of Optional Type
If a subscript Returns a value of optional Type-such as the key subscript of Swift ' s Dictionary
type-place a question mark after the subscript's closing bracket to chain in its optional return value:
-
var testscores = [ "Dave": [86, 82, 84], "Bev": [ 94, 81]]
-
testscores[ "Dave"]?[ 0] = 91
-
< Span class= "VC" >testscores[ "Bev"]?[ 0] + = 1
-
< Span class= "VC" >testscores[ "Brian"]?[ 0] = 72
-
< span class= "C" >//the "Dave" Array is now [,, +] and the "Bev" array is now [+, 94, Bayi]
Optional Chaining as an alternative to forced unwrapping