Swift3.0官方文档与中文翻译对照

Optional Chaining (可选链式调用)

2017-01-20  本文已影响57人  金旭峰

Optional chainingis a process for querying and calling properties, methods, and subscripts on an optional that might currently benil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional isnil, the property, method, or subscript call returnsnil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain isnil.

可选链式调用是一种可以在当前值可能为nil的可选值上请求和调用属性、方法及下标的方法。如果可选值有值,那么调用就会成功;如果可选值是nil,那么调用将返回nil。多个调用可以连接在一起形成一个调用链,如果其中任何一个节点为nil,整个调用链都会失败,即返回nil。

NOTE

Optional chaining in Swift is similar to messagingnilin Objective-C, but in a way that works for any type, and that can be checked for success or failure.

Swift 的可选链式调用和 Objective-C 中向nil发送消息有些相像,但是 Swift 的可选链式调用可以应用于任意类型,并且能检查调用是否成功。

Optional Chaining as an Alternative to Forced Unwrapping (使用可选链式调用代替强制展开)

You specify optional chaining by placing a question mark (?) after the optional value on which you wish to call a property, method or subscript if the optional is non-nil. This is very similar to placing an exclamation mark (!) after an optional value to force the unwrapping of its value. The main difference is that optional chaining fails gracefully when the optional isnil, whereas forced unwrapping triggers a runtime error when the optional isnil.

通过在想调用的属性、方法、或下标的可选值后面放一个问号(?),可以定义一个可选链。这一点很像在可选值后面放一个叹号(!)来强制展开它的值。它们的主要区别在于当可选值为空时可选链式调用只会调用失败,然而强制展开将会触发运行时错误。

To reflect the fact that optional chaining can be called on anilvalue, the result of an optional chaining call is always an optional value, even if the property, method, or subscript you are querying returns a nonoptional value. You can use this optional return value to check whether the optional chaining call was successful (the returned optional contains a value), or did not succeed due to anilvalue in the chain (the returned optional value isnil).

为了反映可选链式调用可以在空值(nil)上调用的事实,不论这个调用的属性、方法及下标返回的值是不是可选值,它的返回结果都是一个可选值。你可以利用这个返回值来判断你的可选链式调用是否调用成功,如果调用有返回值则说明调用成功,返回nil则说明调用失败。

Specifically, the result of an optional chaining call is of the same type as the expected return value, but wrapped in an optional. A property that normally returns anIntwill return anInt?when accessed through optional chaining.

特别地,可选链式调用的返回结果与原本的返回结果具有相同的类型,但是被包装成了一个可选值。例如,使用可选链式调用访问属性,当可选链式调用成功时,如果属性原本的返回结果是Int类型,则会变为Int?类型。

The next several code snippets demonstrate how optional chaining differs from forced unwrapping and enables you to check for success.

下面几段代码将解释可选链式调用和强制展开的不同。

First, two classes calledPersonandResidenceare defined:

首先定义两个类Person和Residence:

class Person{

    var residence:Residence?

}

class Residence{

    var numberOfRooms=1

}

Residenceinstances have a singleIntproperty callednumberOfRooms, with a default value of1.Personinstances have an optionalresidenceproperty of typeResidence?.

Residence有一个Int类型的属性numberOfRooms,其默认值为1。Person具有一个可选的residence属性,其类型为Residence?。

If you create a newPersoninstance, itsresidenceproperty is default initialized tonil, by virtue of being optional. In the code below,johnhas aresidenceproperty value ofnil:

假如你创建了一个新的Person实例,它的residence属性由于是是可选型而将初始化为nil,在下面的代码中,john有一个值为nil的residence属性:

let john=Person()

If you try to access thenumberOfRoomsproperty of this person’sresidence, by placing an exclamation mark afterresidenceto force the unwrapping of its value, you trigger a runtime error, because there is noresidencevalue to unwrap:

如果使用叹号(!)强制展开获得这个john的residence属性中的numberOfRooms值,会触发运行时错误,因为这时residence没有可以展开的值:

let roomCount=john.residence!.numberOfRooms

// this triggers a runtime error

The code above succeeds whenjohn.residencehas a non-nilvalue and will setroomCountto anIntvalue containing the appropriate number of rooms. However, this code always triggers a runtime error whenresidenceisnil, as illustrated above.

john.residence为非nil值的时候,上面的调用会成功,并且把roomCount设置为Int类型的房间数量。正如上面提到的,当residence为nil的时候上面这段代码会触发运行时错误。

Optional chaining provides an alternative way to access the value ofnumberOfRooms. To use optional chaining, use a question mark in place of the exclamation mark:

可选链式调用提供了另一种访问numberOfRooms的方式,使用问号(?)来替代原来的叹号(!):

if let roomCount=john.residence?.numberOfRooms{

    print("John's residence has\(roomCount)room(s).")

} else {

    print("Unable to retrieve the number of rooms.")

}

// Prints "Unable to retrieve the number of rooms."

This tells Swift to “chain” on the optionalresidenceproperty and to retrieve the value ofnumberOfRoomsifresidenceexists.

在residence后面添加问号之后,Swift 就会在residence不为nil的情况下访问numberOfRooms。

Because the attempt to accessnumberOfRoomshas the potential to fail, the optional chaining attempt returns a value of typeInt?, or “optionalInt”. Whenresidenceisnil, as in the example above, this optionalIntwill also benil, to reflect the fact that it was not possible to accessnumberOfRooms. The optionalIntis accessed through optional binding to unwrap the integer and assign the nonoptional value to theroomCountvariable.

因为访问numberOfRooms有可能失败,可选链式调用会返回Int?类型,或称为“可选的Int”。如上例所示,当residence为nil的时候,可选的Int将会为nil,表明无法访问numberOfRooms。访问成功时,可选的Int值会通过可选绑定展开,并赋值给非可选类型的roomCount常量。

Note that this is true even thoughnumberOfRoomsis a nonoptionalInt. The fact that it is queried through an optional chain means that the call tonumberOfRoomswill always return anInt?instead of anInt.

要注意的是,即使numberOfRooms是非可选的Int时,这一点也成立。只要使用可选链式调用就意味着numberOfRooms会返回一个Int?而不是Int。

You can assign aResidenceinstance tojohn.residence, so that it no longer has anilvalue:

可以将一个Residence的实例赋给john.residence,这样它就不再是nil了:

john.residence=Residence()

john.residencenow contains an actualResidenceinstance, rather thannil. If you try to accessnumberOfRoomswith the same optional chaining as before, it will now return anInt?that contains the defaultnumberOfRoomsvalue of1:

john.residence现在包含一个实际的Residence实例,而不再是nil。如果你试图使用先前的可选链式调用访问numberOfRooms,它现在将返回值为1的Int?类型的值:

if let roomCount=john.residence?.numberOfRooms{

    print("John's residence has\(roomCount)room(s).")

} else {

    print("Unable to retrieve the number of rooms.")

}

// Prints "John's residence has 1 room(s)."

Defining Model Classes for Optional Chaining (为可选链式调用定义模型类)

You can use optional chaining with calls to properties, methods, and subscripts that are more than one level deep. This enables you to drill down into subproperties within complex models of interrelated types, and to check whether it is possible to access properties, methods, and subscripts on those subproperties.

通过使用可选链式调用可以调用多层属性、方法和下标。这样可以在复杂的模型中向下访问各种子属性,并且判断能否访问子属性的属性、方法或下标。

The code snippets below define four model classes for use in several subsequent examples, including examples of multilevel optional chaining. These classes expand upon thePersonandResidencemodel from above by adding aRoomandAddressclass, with associated properties, methods, and subscripts.

下面这段代码定义了四个模型类,这些例子包括多层可选链式调用。为了方便说明,在Person和Residence的基础上增加了Room类和Address类,以及相关的属性、方法以及下标。

ThePersonclass is defined in the same way as before:

Person类的定义基本保持不变:

class Person{

    var residence:Residence?

}

TheResidenceclass is more complex than before. This time, theResidenceclass defines a variable property calledrooms, which is initialized with an empty array of type[Room]:

Residence类比之前复杂些,增加了一个名为rooms的变量属性,该属性被初始化为[Room]类型的空数组:

class Residence{

   va rrooms= [Room]()

    var numberOfRooms:Int{

        return rooms.count

    }

    subscript(i:Int) ->Room{

        get{

            returnrooms[i]

        }

        set{

            rooms[i] =newValue

        }

}

func printNumberOfRooms() {

    print("The number of rooms is\(numberOfRooms)")

}

var address:Address?

}

Because this version ofResidencestores an array ofRoominstances, itsnumberOfRoomsproperty is implemented as a computed property, not a stored property. The computednumberOfRoomsproperty simply returns the value of thecountproperty from theroomsarray.

现在Residence有了一个存储Room实例的数组,numberOfRooms属性被实现为计算型属性,而不是存储型属性。numberOfRooms属性简单地返回rooms数组的count属性的值。

As a shortcut to accessing itsroomsarray, this version ofResidenceprovides a read-write subscript that provides access to the room at the requested index in theroomsarray.

Residence还提供了访问rooms数组的快捷方式,即提供可读写的下标来访问rooms数组中指定位置的元素。

This version ofResidencealso provides a method calledprintNumberOfRooms, which simply prints the number of rooms in the residence.

此外,Residence还提供了printNumberOfRooms方法,这个方法的作用是打印numberOfRooms的值。

Finally,Residencedefines an optional property calledaddress, with a type ofAddress?. TheAddressclass type for this property is defined below.

最后,Residence还定义了一个可选属性address,其类型为Address?。Address类的定义在下面会说明。

TheRoomclass used for theroomsarray is a simple class with one property calledname, and an initializer to set that property to a suitable room name:

Room类是一个简单类,其实例被存储在rooms数组中。该类只包含一个属性name,以及一个用于将该属性设置为适当的房间名的初始化函数:

class Room{

    let name:String

    init(name:String) {self.name=name}

}

The final class in this model is calledAddress. This class has three optional properties of typeString?. The first two properties,buildingNameandbuildingNumber, are alternative ways to identify a particular building as part of an address. The third property,street, is used to name the street for that address:

最后一个类是Address,这个类有三个String?类型的可选属性。buildingName以及buildingNumber属性分别表示某个大厦的名称和号码,第三个属性street表示大厦所在街道的名称:

class Address{

    var buildingName:String?

    var buildingNumber:String?

    var street:String?

    func buildingIdentifier() ->String? {

        if buildingNumber!=nil&&street!=nil{

            return"\(buildingNumber)\(street)"

        } else if buildingName!=nil{

            returnbuildingName

        } else {

            returnnil

        }

    }

}

TheAddressclass also provides a method calledbuildingIdentifier(), which has a return type ofString?. This method checks the properties of the address and returnsbuildingNameif it has a value, orbuildingNumberconcatenated withstreetif both have values, ornilotherwise.

Address类提供了buildingIdentifier()方法,返回值为String?。 如果buildingName有值则返回buildingName。或者,如果buildingNumber和street均有值则返回buildingNumber。否则,返回nil。

Accessing Properties Through Optional Chaining (通过可选链式调用访问属性)

As demonstrated inOptional Chaining as an Alternative to Forced Unwrapping, you can use optional chaining to access a property on an optional value, and to check if that property access is successful.

正如使用可选链式调用代替强制展开中所述,可以通过可选链式调用在一个可选值上访问它的属性,并判断访问是否成功。

Use the classes defined above to create a newPersoninstance, and try to access itsnumberOfRoomsproperty as before:

下面的代码创建了一个Person实例,然后像之前一样,尝试访问numberOfRooms属性:

let john=Person()

if let roomCount=john.residence?.numberOfRooms{

       print("John's residence has\(roomCount)room(s).")

} else {

     print("Unable to retrieve the number of rooms.")

}

// Prints "Unable to retrieve the number of rooms."

Becausejohn.residenceisnil, this optional chaining call fails in the same way as before.

因为john.residence为nil,所以这个可选链式调用依旧会像先前一样失败。

You can also attempt to set a property’s value through optional chaining:

还可以通过可选链式调用来设置属性值:

let someAddress=Address()

someAddress.buildingNumber="29"

someAddress.street="Acacia Road"

john.residence?.address=someAddress

In this example, the attempt to set theaddressproperty ofjohn.residencewill fail, becausejohn.residenceis currentlynil.

在这个例子中,通过john.residence来设定address属性也会失败,因为john.residence当前为nil。

The assignment is part of the optional chaining, which means none of the code on the right hand side of the=operator is evaluated. In the previous example, it’s not easy to see thatsomeAddressis never evaluated, because accessing a constant doesn’t have any side effects. The listing below does the same assignment, but it uses a function to create the address. The function prints “Function was called” before returning a value, which lets you see whether the right hand side of the=operator was evaluated.

上面代码中的赋值过程是可选链式调用的一部分,这意味着可选链式调用失败时,等号右侧的代码不会被执行。对于上面的代码来说,很难验证这一点,因为像这样赋值一个常量没有任何副作用。下面的代码完成了同样的事情,但是它使用一个函数来创建Address实例,然后将该实例返回用于赋值。该函数会在返回前打印“Function was called”,这使你能验证等号右侧的代码是否被执行。

func createAddress() ->Address{

    print("Function was called.")

    let someAddress=Address()

    someAddress.buildingNumber="29"

    someAddress.street="Acacia Road"

    return someAddress

}

john.residence?.address=createAddress()

You can tell that thecreateAddress()function isn’t called, because nothing is printed.

没有任何打印消息,可以看出createAddress()函数并未被执行。

Calling Methods Through Optional Chaining (通过可选链式调用调用方法)

You can use optional chaining to call a method on an optional value, and to check whether that method call is successful. You can do this even if that method does not define a return value.

可以通过可选链式调用来调用方法,并判断是否调用成功,即使这个方法没有返回值。

TheprintNumberOfRooms()method on theResidenceclass prints the current value ofnumberOfRooms. Here’s how the method looks:

Residence类中的printNumberOfRooms()方法打印当前的numberOfRooms值,如下所示:

func printNumberOfRooms() {

    print("The number of rooms is\(numberOfRooms)")

}

This method does not specify a return type. However, functions and methods with no return type have an implicit return type ofVoid, as described inFunctions Without Return Values. This means that they return a value of(), or an empty tuple.

这个方法没有返回值。然而,没有返回值的方法具有隐式的返回类型Void,如无返回值函数中所述。这意味着没有返回值的方法也会返回(),或者说空的元组。

If you call this method on an optional value with optional chaining, the method’s return type will beVoid?, notVoid, because return values are always of an optional type when called through optional chaining. This enables you to use anifstatement to check whether it was possible to call theprintNumberOfRooms()method, even though the method does not itself define a return value. Compare the return value from theprintNumberOfRoomscall againstnilto see if the method call was successful:

如果在可选值上通过可选链式调用来调用这个方法,该方法的返回类型会是Void?,而不是Void,因为通过可选链式调用得到的返回值都是可选的。这样我们就可以使用if语句来判断能否成功调用printNumberOfRooms()方法,即使方法本身没有定义返回值。通过判断返回值是否为nil可以判断调用是否成功:

if john.residence?.printNumberOfRooms() !=nil{

    print("It was possible to print the number of rooms.")

} else {

    print("It was not possible to print the number of rooms.")

}

// Prints "It was not possible to print the number of rooms."

The same is true if you attempt to set a property through optional chaining. The example above inAccessing Properties Through Optional Chainingattempts to set anaddressvalue forjohn.residence, even though theresidenceproperty isnil. Any attempt to set a property through optional chaining returns a value of typeVoid?, which enables you to compare againstnilto see if the property was set successfully:

同样的,可以据此判断通过可选链式调用为属性赋值是否成功。在上面的通过可选链式调用访问属性的例子中,我们尝试给john.residence中的address属性赋值,即使residence为nil。通过可选链式调用给属性赋值会返回Void?,通过判断返回值是否为nil就可以知道赋值是否成功:

if (john.residence?.address=someAddress) !=nil{

    print("It was possible to set the address.")

} else {

    print("It was not possible to set the address.")

}

// Prints "It was not possible to set the address."

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 whether that subscript call is successful.

通过可选链式调用,我们可以在一个可选值上访问下标,并且判断下标调用是否成功。

NOTE

When you access a subscript on an optional value through optional chaining, you place the question markbeforethe subscript’s brackets, not after. The optional chaining question mark always follows immediately after the part of the expression that is optional.

通过可选链式调用访问可选值的下标时,应该将问号放在下标方括号的前面而不是后面。可选链式调用的问号一般直接跟在可选表达式的后面。

The example below tries to retrieve the name of the first room in theroomsarray of thejohn.residenceproperty using the subscript defined on theResidenceclass. Becausejohn.residenceis currentlynil, the subscript call fails:

下面这个例子用下标访问john.residence属性存储的Residence实例的rooms数组中的第一个房间的名称,因为john.residence为nil,所以下标调用失败了:

if let firstRoomName=john.residence?[0].name{

    print("The first room name is\(firstRoomName).")

} else {

    print("Unable to retrieve the first room name.")

}

// Prints "Unable to retrieve the first room name."

The optional chaining question mark in this subscript call is placed immediately afterjohn.residence, before the subscript brackets, becausejohn.residenceis the optional value on which optional chaining is being attempted.

在这个例子中,问号直接放在john.residence的后面,并且在方括号的前面,因为john.residence是可选值。

Similarly, you can try to set a new value through a subscript with optional chaining:

类似的,可以通过下标,用可选链式调用来赋值:

john.residence?[0] =Room(name:"Bathroom")

This subscript setting attempt also fails, becauseresidenceis currentlynil.

这次赋值同样会失败,因为residence目前是nil。

If you create and assign an actualResidenceinstance tojohn.residence, with one or moreRoominstances in itsroomsarray, you can use theResidencesubscript to access the actual items in theroomsarray through optional chaining:

如果你创建一个Residence实例,并为其rooms数组添加一些Room实例,然后将Residence实例赋值给john.residence,那就可以通过可选链和下标来访问数组中的元素:

let johnsHouse=Residence()

johnsHouse.rooms.append(Room(name:"Living Room"))

johnsHouse.rooms.append(Room(name:"Kitchen"))

john.residence=johnsHouse

if let firstRoomName=john.residence?[0].name{

    print("The first room name is\(firstRoomName).")

} else {

   print("Unable to retrieve the first room name.")

}

// Prints "The first room name is Living Room."

Accessing Subscripts of Optional Type (访问可选类型的下标)

If a subscript returns a value of optional type—such as the key subscript of Swift’sDictionarytype—place a question markafterthe subscript’s closing bracket to chain on its optional return value:

如果下标返回可选类型值,比如 Swift 中Dictionary类型的键的下标,可以在下标的结尾括号后面放一个问号来在其可选返回值上进行可选链式调用:

var testScores= ["Dave": [86,82,84],"Bev": [79,94,81]]

testScores["Dave"]?[0] =91

testScores["Bev"]?[0] +=1

testScores["Brian"]?[0] =72

// the "Dave" array is now [91, 82, 84] and the "Bev" array is now [80, 94, 81]

The example above defines a dictionary calledtestScores, which contains two key-value pairs that map aStringkey to an array ofIntvalues. The example uses optional chaining to set the first item in the"Dave"array to91; to increment the first item in the"Bev"array by1; and to try to set the first item in an array for a key of"Brian". The first two calls succeed, because thetestScoresdictionary contains keys for"Dave"and"Bev". The third call fails, because thetestScoresdictionary does not contain a key for"Brian".

上面的例子中定义了一个testScores数组,包含了两个键值对,把String类型的键映射到一个Int值的数组。这个例子用可选链式调用把"Dave"数组中第一个元素设为91,把"Bev"数组的第一个元素+1,然后尝试把"Brian"数组中的第一个元素设为72。前两个调用成功,因为testScores字典中包含"Dave"和"Bev"这两个键。但是testScores字典中没有"Brian"这个键,所以第三个调用失败。

Linking Multiple Levels of Chaining (连接多层可选链式调用)

You can link together multiple levels of optional chaining to drill down to properties, methods, and subscripts deeper within a model. However, multiple levels of optional chaining do not add more levels of optionality to the returned value.

可以通过连接多个可选链式调用在更深的模型层级中访问属性、方法以及下标。然而,多层可选链式调用不会增加返回值的可选层级。

To put it another way:

也就是说:

1. If the type you are trying to retrieve is not optional, it will become optional because of the optional chaining.

如果你访问的值不是可选的,可选链式调用将会返回可选值。

2. If the type you are trying to retrieve isalreadyoptional, it will not becomemoreoptional because of the chaining.

如果你访问的值就是可选的,可选链式调用不会让可选返回值变得“更可选”。

Therefore:

因此:

1. If you try to retrieve anIntvalue through optional chaining, anInt?is always returned, no matter how many levels of chaining are used.

通过可选链式调用访问一个Int值,将会返回Int?,无论使用了多少层可选链式调用。

2. Similarly, if you try to retrieve anInt?value through optional chaining, anInt?is always returned, no matter how many levels of chaining are used.

类似的,通过可选链式调用访问Int?值,依旧会返回Int?值,并不会返回Int??。

The example below tries to access thestreetproperty of theaddressproperty of theresidenceproperty ofjohn. There aretwolevels of optional chaining in use here, to chain through theresidenceandaddressproperties, both of which are of optional type:

下面的例子尝试访问john中的residence属性中的address属性中的street属性。这里使用了两层可选链式调用,residence以及address都是可选值:

if let johnsStreet=john.residence?.address?.street{

    print("John's street name is\(johnsStreet).")

} else {

    print("Unable to retrieve the address.")

}

// Prints "Unable to retrieve the address."

The value ofjohn.residencecurrently contains a validResidenceinstance. However, the value ofjohn.residence.addressis currentlynil. Because of this, the call tojohn.residence?.address?.streetfails.

john.residence现在包含一个有效的Residence实例。然而,john.residence.address的值当前为nil。因此,调用john.residence?.address?.street会失败。

Note that in the example above, you are trying to retrieve the value of thestreetproperty. The type of this property isString?. The return value ofjohn.residence?.address?.streetis therefore alsoString?, even though two levels of optional chaining are applied in addition to the underlying optional type of the property.

需要注意的是,上面的例子中,street的属性为String?。john.residence?.address?.street的返回值也依然是String?,即使已经使用了两层可选链式调用。

If you set an actualAddressinstance as the value forjohn.residence.address, and set an actual value for the address’sstreetproperty, you can access the value of thestreetproperty through multilevel optional chaining:

如果为john.residence.address赋值一个Address实例,并且为address中的street属性设置一个有效值,我们就能过通过可选链式调用来访问street属性:

let johnsAddress=Address()

johnsAddress.buildingName="The Larches"

johnsAddress.street="Laurel Street"

john.residence?.address=johnsAddress

if let johnsStreet=john.residence?.address?.street{

    print("John's street name is\(johnsStreet).")

} else {

   print("Unable to retrieve the address.")

}

// Prints "John's street name is Laurel Street."

In this example, the attempt to set theaddressproperty ofjohn.residencewill succeed, because the value ofjohn.residencecurrently contains a validResidenceinstance.

在上面的例子中,因为john.residence包含一个有效的Residence实例,所以对john.residence的address属性赋值将会成功。

Chaining on Methods with Optional Return Values (在方法的可选返回值上进行可选链式调用)

The previous example shows how to retrieve the value of a property of optional type through optional chaining. You can also use optional chaining to call a method that returns a value of optional type, and to chain on that method’s return value if needed.

上面的例子展示了如何在一个可选值上通过可选链式调用来获取它的属性值。我们还可以在一个可选值上通过可选链式调用来调用方法,并且可以根据需要继续在方法的可选返回值上进行可选链式调用。

The example below calls theAddressclass’sbuildingIdentifier()method through optional chaining. This method returns a value of typeString?. As described above, the ultimate return type of this method call after optional chaining is alsoString?:

在下面的例子中,通过可选链式调用来调用Address的buildingIdentifier()方法。这个方法返回String?类型的值。如上所述,通过可选链式调用来调用该方法,最终的返回值依旧会是String?类型:

if let buildingIdentifier=john.residence?.address?.buildingIdentifier() {

    print("John's building identifier is\(buildingIdentifier).")

}

// Prints "John's building identifier is The Larches."

If you want to perform further optional chaining on this method’s return value, place the optional chaining question markafterthe method’s parentheses:

如果要在该方法的返回值上进行可选链式调用,在方法的圆括号后面加上问号即可:

if let 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\".")

}

}

// Prints "John's building identifier begins with "The"."

NOTE

In the example above, you place the optional chaining question markafterthe parentheses, because the optional value you are chaining on is thebuildingIdentifier()method’s return value, and not thebuildingIdentifier()method itself.

在上面的例子中,在方法的圆括号后面加上问号是因为你要在buildingIdentifier()方法的可选返回值上进行可选链式调用,而不是方法本身。

上一篇下一篇

猜你喜欢

热点阅读