Learn Swift--optional chain

Source: Internet
Author: User

Nullable chained calls

A nullable chain call is a procedure that can request and invoke properties, methods, and subscripts, and its nullability is reflected in the possibility that the target of the request or call is currently empty (nil). If the nullable target has a value, the call succeeds , and if the selected target is null (nil), the call returns Null (NIL). Multiple successive calls can be chained together to form a call chain, and if any one of the nodes is empty (nil) will cause the entire chain call to fail.

use a nullable chained tone to force the expansion

You can define a nullable chain by placing a question mark after the nullable value of the property, method, or subscript that you want to invoke. This is much like placing an exclamation mark after a nullable value (! ) to force the expansion of the value. The main difference between them is that when a nullable value is empty, a nullable chain is simply a call failure, but forcing the expansion will trigger a run-time error.

To reflect that a nullable chain call can be called on an empty object (nil), the returned result is a nullable value, regardless of whether the returned value of the call's property, method, subscript, and so on is a nullable value. You can use this return value to determine whether your nullable chain call succeeds, and if the call has a return value, the call succeeds and the call nil fails.

In particular, the return result of a nullable chain call has the same type as the original return result, but is packaged as a nullable type value. When a nullable chain call succeeds, the result of a type that should be returned Int will return the Int? type.

The following is an example of a run-time error:
Class Residence {    var numberofrooms = 1}class person {    var residence:residence?} Let John = person ()//The following line of code will give an error, because John's residence is nullable, John was initialized and did not assign a value to residence, arbitrarily residence to nil//john.residence! is forced to expand, residence is empty (nil), resulting in a run-time error of let Roomcount = john.residence!. Numberofrooms
The following is a safe notation:
Class Residence {    var numberofrooms = 1}class person {    var residence:residence?} Let John = person () if let Roomcount = John.residence?. numberofrooms {    print ("John ' s residence has \ (Roomcount) (s).")} else {    print ("Unable to retrieve the number O F rooms. ")}

to define a model class for a nullable chained call

Multi-layered properties, methods, and subscripts can be called by using a nullable chain call. This allows the various sub-properties to be accessed down through various models. and determine whether you can access properties, methods, or subscripts of child properties.

The person class remains the same:
Class Person {    var residence:residence?}
ResidenceThe analogy is more complex and adds a RoomAn empty array of type room
Class Residence {    var rooms = [guest] ()    var numberofrooms:int {        return rooms.count    }    Subscript ( Index:int)------{        get {            return Rooms[index]        }        set {            Rooms[index] = newvalue        }    }    Func printnumberofrooms () {        print ("The number of rooms is \ (numberofrooms)")    }    var address:address?}
Class Roomis a simple class that contains only one property name, and an initialization function:
Class Guest {Let    name:string    init (name:string) {        self.name = name    }}
The last class is Address, there are three of this class String?The Nullable property of the type. buildingNameAnd buildingNumberThe property represents the name and number of the building used to represent a particular building. The third attribute represents the name of the street where the building is located:
Class Address {    var buildingname:string?    var buildingnumber:string?    var street:string?    Func buildingidentifier (), String? {        if buildingname! = nil {            return buildingname        } else if buildingnumber! = nil {            return buildingnumber        } else {            return nil        }}    }

accessing properties via a nullable chained call
Let John = person () if let Roomcount = John.residence?. numberofrooms {    print ("John ' s residence has \ (Roomcount) (s).")} else {    print ("Unable to retrieve the number O F rooms. ")    Print this line}let someaddress = Address () Someaddress.buildingnumber = "Someaddress.buildingname" = "Acacia Road" John.residence?. Address = someaddress//because John's residence attribute is still empty, even if the address is now set, the print (john.residence) will not succeed. Address?. Buildingname)    //Nil

calling a method with a nullable chain callFirst look at the method of the eye:
Func printnumberofrooms () {        print ("The number of rooms is \ (numberofrooms)")    }

Note: This method does not return a value. However, methods that do not return a value implicitly return a Void type, which means that a method that does not return a value also returns () or an empty tuple.

If the method is called by a nullable chained call on a nullable value, the return type of the method is Void? , not Void , because the return value obtained through a nullable chain call is nullable.

So that we can use ifStatement to determine whether a successful call printNumberOfRooms()method, even if the method itself does not define a return value. Whether the return value is nilYou can tell if the call was successful:
Let John = person () if john.residence?. Printnumberofrooms ()! = nil {    print ("It is possible to print the number of rooms.")} else {    //print out this line    ("I T was wasn't possible to print the number of rooms. ")}

Similarly, it is possible to determine whether a value is successfully assigned to a property through a nullable chain call. In the example above, we try to john.residence assign a value to a address property in, even if residence nil . Assigning a value to an attribute via a nullable chain call returns Void?。

By judging whether the return value is nilYou can tell if the assignment was successful:
Let John = person () Let someaddress = Address () Someaddress.buildingnumber = "Someaddress.street" = "Acacia Road" john.res Idence?. Address = Someaddressif (john.residence?.  Address = someaddress)! = Nil {    print ("It is possible to set the address.")} else {    print ("It is not possible to  Set the address. ") Call this line}

access Subscript via a nullable chain transfer

With a nullable chain call, we can use subscripts to read or write to nullable values, and to determine if the subscript call was successful.

Note: When you access the subscript of a nullable value through a nullable chain call, you should place the question mark in front of the subscript square brackets instead of behind. A question mark that can be called with an empty chain is usually followed directly by a nullable expression.

Let John = person () if let Firstroomname = John.residence? [0].name {    print ("The first Firstroomname.")} else {    print ("Unable to retrieve the first" name .")} Print: "Unable to retrieve the first." Because John's Residence property is empty, the access to its subscript will definitely return null (NIL)//can also be assigned through a nullable chain, but the following code will fail to assign a value, if residence has a value will be successful john.residence? [0] = Guest box (name: "Room1")
Let's look at a successful example:
Let John = person () Let House = Residence () house.rooms.append (name: "Living)") House.rooms.append (name: " Kitchen ")) John.residence = House  //Assignment Residence property now has value, no longer nil if let Firstroomname = john.residence?[ 0].name {    print ("The first guest name is \ (firstroomname).")} else {    print ("Unable to retrieve the first" name. ")}//print out: The first guest name is Living.

to access the subscript of a nullable type

If the subscript returns a nullable type value, such as a subscript in Swift Dictionary key . You can link the nullable return value of the subscript by placing a question mark after the closing parenthesis of the subscript:

var testscores = ["Dave": [, "Bev", "81]]testscores[", "Dave"]? [0] = 91testscores["Bev"]? [0] + = 1if (testscores["Brian"]?[ 0] = scores)! = Nil {    print ("Brian's" is \ (testscores["Brian"]) "} else {    print (" Haven ' t Brian ")}//print:" Haven ' t Brian "Print" ("Dave's scores is \" (testscores["Dave"]), Bev's scores is \ (testscores["Bev"])//print: "Dave's scores is Option Al ([Bev], scores is Optional ([80, 95, 81]) "

Multi-layer links

You can access properties, methods, and subscripts down through multiple links with several nullable chaining. However, the nullability of the return value is not added to the multi-layer nullable chain call.

Other words:

    • If the value you are accessing is not nullable, the nullable chain call will put back a nullable value.
    • If the value you are accessing is already nullable, it will not become "more" nullable through a nullable chain call, it is still nullable

So:

    • Accessing a value through a nullable chain call Int will return Int? , but how many times can a nullable chain call be made.
    • Similarly, accessing a value through a nullable chained call Int? does not become more nullable, it is also an int? type
Let John = person () Let House = Residence () house.rooms.append (name: "Living)") House.rooms.append (name: " Kitchen ")) John.residence = House if let street = John.residence?. Address?. Street {    print ("John's street name is \ (street).")} else {    print ("Unable to retrieve the address.")} Print out: "Unable to retrieve the address."
The following are examples of success:
Let John = person () Let House = Residence () house.rooms.append (name: "Living)") House.rooms.append (name: " Kitchen ")) John.residence = House Let address = address () Address.buildingname =" The larches "Address.street =" Laurel stree T "John.residence?". Address = addressif Let street = John.residence?. Address?. Street {    print ("John's street name is \ (street).")} else {    print ("Unable to retrieve the address.")} Print: "John's street name is Laurel Street."

links to functions that return nullable values

You can invoke a method that returns a nullable value through a nullable chained call, and you can continue to link to a nullable value.

Let John = person () Let House = Residence () house.rooms.append (name: "Living)") House.rooms.append (name: " Kitchen ")) John.residence = House  //Assignment Residence property now has a value, it's no longer nil. Let address = address () Address.buildingname =" The larches "Address.street =" Laurel Street "John.residence? Address = Addressif Let identifier = John.residence?. Address?. Buildingidentifier () {    print ("John ' s building identifier is \ (identifier).")} Further access via optional chain because Buildingidentifier () returns a string, after Buildingidentifier () add an If let beginwiththe = John.residence?. Address?. Buildingidentifier ()?. Hasprefix ("the") {    print ("John ' s building identifier begins with \" The\ ")} else {    print ("John ' s building identifier does not begin with \" The\ ")} Print: "John ' s building identifier begins with" the "."

Learn Swift--optional chain

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.