可选链式调用是一种可以在当前值可能为nil的可选值上请求和调用属性、方法及下标的方法。如果可选值有值,那么调用就会成功;如果可选值是nil,那么调用将返回nil。多个调用可以连接在一起形成一个调用链,如果其中任何一个节点为nil,整个调用链都会失败,即返回nil。
import UIKit
var str = "Hello, playground"
class Person {
var residence: Residence?
}
class Residence {
var rooms = [Room]()
var numberOfRooms: Int {
return rooms.count
}
subscript(i: Int) -> Room {
get {
return rooms[i]
}
set {
rooms[i] = newValue
}
}
func printNumberOfRooms() {
print("The number of rooms is \(numberOfRooms)")
}
var address: Address?
}
class Room {
let name: String
init(name: String) { self.name = name }
}
class Address {
var buildingName: String?
var buildingNumber: String?
var street: String?
func buildingIdentifier() -> String? {
if buildingName != nil {
return buildingName
} else if buildingNumber != nil && street != nil {
return "\(buildingNumber) \(street)"
} else {
return nil
}
}
}
let john = Person()
//john.residence = Residence()
func createAddress() -> Address {
print("Function was called.")
let someAddress = Address()
someAddress.buildingNumber = "29"
someAddress.street = "Acacia Road"
return someAddress
}
john.residence?.address = createAddress()
let someAddress = Address()
someAddress.buildingNumber = "29"
someAddress.street = "Acacia Road"
let johnsHouse = Residence()
johnsHouse.rooms.append(Room(name: "Living Room"))
johnsHouse.rooms.append(Room(name: "Kitchen"))
john.residence = johnsHouse
//可选链访问属性
if let roomCount = john.residence?.numberOfRooms {
print("John's residence has \(roomCount) rooms")
}else {
print("Unable to retrive the number of rooms")
}
if (john.residence?.address = someAddress) != nil {
print("It was possible to set the address")
} else {
print("It was not possible to set addresss")
}
//可选链调用方法
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")
}
//可选链访问下标
if let firstRoomName = john.residence?[0].name {
print("The first rooom name is \(firstRoomName)")
} else {
print("Unable to retrieve the first room name.")
}
var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
testScores["Dave"]?[0] = 91
testScores["Bev"]?[0] += 1
testScores["Brian"]?[0] = 72
print("test1:\(testScores["Dave"])")
print("test2:\(testScores["Bev"])")
print("test3:\(testScores["Brian"])")
if let buildingIdentifier = john.residence?.address?.buildingIdentifier() {
print("John's building identifier is \(buildingIdentifier)")
}
if let beginWithThe = john.residence?.address?.buildingIdentifier()?.hasPrefix("The") {
if beginWithThe {
print("John's building identifier begin with \"The\" .")
} else {
print("John's building identifier does not begin with \"The\". ")
}
}