An optional chained call (Optional Chaining) is a way to request and invoke properties, methods, and subscripts on an optional value that the current value may be nil. If the optional value has a value, the call succeeds, and if the optional value is nil, the call returns nil. Multiple calls can be joined together to form a chain of calls, and if any one of the nodes is nil, the entire call chain will fail, returning nil.
Swift This function design is very good, does not report null pointer exception, if is in Java, that link object is empty, the report null pointer exception, the program exits unexpectedly, Swift does not, will return a nil, very convenient.
You can define an optional chain by placing a question mark (?) behind the optional value (optional value) of the property, method, or subscript that you want to invoke.
iflet roomCount = john.residence?.numberOfRooms { print("John‘s residence has \(roomCount) room(s)."else { print("Unable to retrieve the number of rooms.")}
Even if residence is nil it will not be reported as abnormal, it would go into the Else branch, very simple.
Accessing properties with optional chained calls
let someAddress = Address()someAddress.buildingNumber"29"someAddress.street"Acacia Road"john.residence?.address = someAddress
Invoking a method with an optional chained call
ifnil { print("It was possible to print the number of rooms."else { print("It was not possible to print the number of rooms.")}
Access subscript via optional chained call
john.residence?[0] = Room(name"Bathroom")
To access the subscript for an optional type
var testScores = ["Dave": [868284"Bev": [799481]]testScores["Dave"]?[091testScores["Bev"]?[0]++testScores["Brian"]?[072
Connecting multi-layer optional chained calls
You can access properties, methods, and subscripts in a deeper model hierarchy by connecting multiple optional chain calls. However, multilayer optional chaining calls do not increase the optional level of the return value.
Other words:
- If the value you are accessing is not optional, an optional chained call will return an optional value.
- The value you access is optional, and an optional chained call does not make the optional return value "more optional".
Optional chained call on the optional return value of the method
iflet beginsWithThe = john.residence?.address?.buildingIdentifier()?.hasPrefix("The") { if beginsWithThe { print("John‘s building identifier begins with \"The\".") else { print("John‘s building identifier does not begin with \"The\".") }}
Learn swift--optional chained calls against Java (Optional Chaining)