Optional chaining is a process that allows you to request and call attributes, methods, and subscripts, its self-sufficiency is reflected in that the current request or call target may be null (nil ). If the self-determined target has a value, the call will succeed. On the contrary, if the selected target is null (NiL), the call will return NULL (nil ). Multiple requests or calls can be linked together to form a chain. If any node is empty (NiL), the entire chain will become invalid.
Note: The self-judgment chain of SWIFT is similar to the message in objective-C, but Swift can be used in any type and the failure or failure can be detected.
Optional chain can replace forced resolution
You can define an optional chain by placing a question mark after the optional value (optional value) of the property, method, or sub-script you want to call. This is similar to placing a declarative symbol behind an optional value to forcibly split the value in the package. The main difference between them is that when the optional value is null, the optional chain fails immediately. However, a general forced resolution will cause a runtime error.
To reflect whether the optional chain can call null (NiL), whether or not the returned values of the properties, methods, and subscripts you call are optional values, the returned results are all optional values. You can use this return value to check whether your optional chain is successfully called. If yes, the call succeeds. If yes, the call fails if NIL is returned.
The returned results of the call of the optional chain have the same type as the original returned results, but the original returned results are encapsulated into an optional value. When the optional chain call is successful, an attribute that should return int will return Int ?.
The following sections of Code explain the differences between the optional chain and forced resolution.
First, define two classes: person and residence.
class Person { var residence: Residence?} class Residence { var numberOfRooms = 1}
Residence has a numberofrooms of the int type and its value is 1. A person has a residence property of self-judgment. Its type is residence ?.
If you create a new person instance, its residence attribute is defined as a user-judgment type, which will be initialized blank by default:
let john = Person()
If you want to use an exclamation point (!) Forcing resolution to obtain the numberofrooms property value of this residence property will cause a runtime error because there is no residence value for resolution.
let roomCount =john.residence!.numberOfRooms
// It will cause a running error
When John. residence is not nil, it runs and sets roomcount to a reasonable value of the int type. However, as mentioned above, when the residence is empty, this code will cause a runtime error.
The optional chain provides another method to obtain numberofrooms. Use optional links and question marks to replace the original! Location:
If let roomcount = John. Residence ?. Numberofrooms {println ("John's residence has \ (roomcount) Room (s ). ")} else {println (" unable to retrieve the number of rooms. ")} // print" Unable toretrieve the number of rooms.
This tells swift to determine residence by link? Property. If residence exists, the value of numberofrooms is retrieved.
This operation may fail to obtain numberofrooms. The optional chain will return Int? Type value, or "self-judgment int ". When the residence is empty (in the previous example), selecting int will be empty, so numberofrooms cannot be accessed first.
Note that even if numberofrooms is not a self-judged int (Int ?) This is also true. As long as the request passes the optional link, it means that the final numberofrooms always returns an int? Instead of Int.
You can define a residence instance for John. residence so that it is no longer blank:
john.residence = Residence()
John. residence now has an actual instance instead of nil. If you want to use the same optional chain as before to obtain numberofroooms, it will return an int containing the default value of 1? :
If let roomcount = John. Residence ?. Numberofrooms {println ("John's residence has \ (roomcount) Room (s ). ")} else {println (" unable to retrieve the number of rooms. ")} // print" John's residence has 1 room (s )".
Define model classes for optional chains
You can use optional links to call attributes, methods, and subscripts in multiple layers. This allows you to use the complex models between them to obtain more underlying attributes and check whether such underlying attributes can be obtained successfully.
The code below defines four model classes to be used later, including multi-layer optional chains. These classes are extended by adding a room and an address class in the above person and residence model.
The person class is defined as before.
class Person { var residence: Residence?}
Residence is more complex than before. This time, it defines a variable "Rooms", which is initialized as an empty array of the room [] type:
class Residence { var rooms = Room[]() var numberOfRooms: Int { return rooms.count } subscript(i: Int) -> Room { return rooms[i] } func printNumberOfRooms() { println("The number of rooms is \(numberOfRooms)") } var address: Address?}
Because residence stores an array of room instances, its numberofrooms attribute value is calculated instead of a fixed storage value. The numberofrooms attribute value is obtained by returning the Count attribute value of the rooms array.
To quickly access the rooms array, residence defines a read-only sub-script, which can be successfully called by inserting the element badge of the array. If the badge exists, the subscript returns the element.
Residence also provides a printnumberofrooms method, that is, a simple number of printed rooms.
Finally, residence defines a self-judgment attribute called address (address ?). The attribute of the address class will be defined later. The room class used for the room array is a very simple class, which has only one name attribute and an initialized device for setting the room name.
class Room { let name: String init(name: String) { self.name = name }}
The final class in this model is called address. It has three self-judgment attributes. The value type is string ?. The first two self-judgment attributes buildingname and buildingnumber are part of the address. They are two ways to define a building. The third property Street is the street name used to name the address:
class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if buildingName { return buildingName } else if buildingNumber { return buildingNumber } else { return nil } }}
The address class also provides a buildingidentifier method. Its return value type is string ?. This method checks the attributes of buildingname and buildingnumber. If buildingname has a value, it will be returned, or if buildingnumber has a value, it will be returned, or if no property has a value, it will return null.
Call attributes through optional links
As described in "Alternative force resolution of optional links" above, you can use the optional values of optional links to obtain attributes and check whether the attributes are obtained successfully. However, you cannot assign values to attributes using optional links.
Use the class defined above to create a person instance, and try again to go to its numberofrooms attribute:
Let John = person () If let roomcount = John. Residence ?. Numberofrooms {println ("John's residence has \ (roomcount) Room (s ). ")} else {println (" unable to retrieve the number of rooms. ")} // print" Unable toretrieve the number of rooms.
Because John. residence is empty, this optional link fails as before, but there is no runtime error.
Call methods using optional links
You can use the optional chain to call the method of the optional value and check whether the method call is successful. Even if this method does not return a value, you can still use the optional chain to achieve this goal.
The printnumberofrooms method of residence prints the current value of numberofrooms. The method is as follows:
func printNumberOfRooms(){ println(“The number of rooms is \(numberOfRooms)”)}
This method does not return values. However, functions and methods without return value types have an implicit return value type void (see function without return values ).
If you use the optional chain to call this method, the return value type of this method will be void ?, Instead of void, because the return value is always optional type (optional type) when the method is called through the optional chain )., Even if this method does not define the return value, you can use the if statement to check whether the printnumberofrooms method can be successfully called: if the method is successfully called through the optional chain, the implicit return value of printnumberofrooms will be void, if not, Nil is returned:
If John. Residence ?. Printnumberofrooms () {println ("it was possible to print the number of rooms. ")} else {println (" it was not possible to print the number of rooms. ")} // print" It was notpossible to print the number of rooms. ".
Use the optional link to call the subscript
You can use the optional link to obtain the value from the sub-script and check whether the Sub-script call is successful. However, you cannot use the optional link to set the sub-code.
Note: When you use the optional link to obtain the sub-script, you should put the question mark in front of the sub-script brackets instead of the following. The question mark of the optional link is generally followed by the self-judgment Expression statement.
The following example uses the child script defined in the residence class to obtain the name of the first room in the john. Residence array. Because John. residence is now nil, the sub-script call fails.
If let firstroomname = John. residence? [0]. name {println ("the first room name is \ (firstroomname ). ")} else {println (" unable to retrieve the first room name. ")} // print" Unable toretrieve the first room name. ".
In a sub-code call, the question mark of the optional link directly follows John. Residence, before the sub-script brackets, because John. residence is the optional value that the optional link tries to obtain.
If you create a residence instance for John. residence, and there is one or more room instances in his room array, you can use the optional chain to get the instances in the room array through the residence sub-script:
Let johnshouse = residence () johnshouse. rooms + = room (name: "livingroom") johnshouse. rooms + = room (name: "Kitchen") John. residence = johnshouse if let firstroomname = John. residence? [0]. name {println ("thefirst room name is \ (firstroomname ). ")} else {println (" unable to retrieve the first room name. ")} // print" The firstroom name is living room. ".
Connect multiple links
You can connect multiple layers of optional links to obtain the attribute methods and subscripts of the lower layers in the model. However, you cannot add more layers than the available values returned by the multi-layer optional chain. That is to say:
If the type you are trying to obtain is not an optional type, it will become an optional type because the optional chain is used. If the type you are trying to obtain is already an optional type, it will not improve self-attention because of the optional chain.
Therefore:
If you try to obtain the int value through the optional chain, no matter how many layers of links are used, the returned value is always Int ?. Similarly, if you try to obtain an int through the optional chain? Value, no matter how many layers of links are used, the returned value is always Int ?.
The following example attempts to obtain the street attribute of address in John's residence attribute. Two optional links are used to contact the residence and address attributes. Both of them are optional:
If let johnsstreet = John. Residence ?. Address ?. Street {println ("John's street name is \ (johnsstreet ). ")} else {println (" unable to retrieve the address. ")} // print" Unable toretrieve the address. ".
The value of John. residence now contains a residence instance, but John. residence. Address is now nil, so John. Residence ?. Address ?. Street call failed.
The preceding example shows that you are trying to obtain the Street property value. The type of this attribute is string ?. Therefore, although two optional links are used before the optional type attribute, John. Residence ?. Address ?. The Return Value Type of street is also string ?.
If you set an instance for address as the value of John. residence. Address and set an actual value for the street attribute of address, you can obtain the attribute value through multiple layers of optional chains.
Let johnsaddress = address () johnsaddress. buildingname = "thelarches" johnsaddress. Street = "Laurel lstreet" 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. ")} // print" John 'sstreet name is Laurel Street. ".
It is worth noting that "!" When defining the address instance (John. residence. Address ). The John. Residence attribute is an optional type, so you need to use it before getting the address attribute! Parse to obtain its actual value.
Method for judging the return value by link
The previous example explains how to obtain optional type attribute values through the optional chain. You can also call the method that returns the optional type value and link the returned value of the method as needed.
The following example calls the buildingidentifier method in the Address class through the optional chain. The Return Value Type of this method is string ?. As mentioned above, the final return value type of this method after the optional chain call is still string? :
If let buildingidentifier = John. Residence ?. Address ?. Buildingidentifier () {println ("John's building identifier is \ (buildingidentifier).")} // print "John's building identifier is the larches .".
If you want to further execute the optional link for the method return value, place the optional link question mark after the method brackets:
If let upper = John. Residence ?. Address ?. Buildingidentifier ()?. Uppercasestring {println ("John's uppercase building identifier is \ (upper).")} // print "John's uppercasebuilding identifier is the larches .".
Note: In the preceding example, you put the optional question mark after the brackets because the optional value you want to link is the returned value of the buildingidentifier method, not the buildingidentifier method itself.