Swift optional chain

Optional Chaining is a process that can request and call properties, methods, and sub-scripts that may target nil.

The optional chain returns two values:

  • If the target has a value, the call succeeds and the value is returned

  • If the target is nil, the call returns nil

Multiple requests or calls can be linked to a chain, and if either node is nil, the entire chain will fail.


Optional chains replace forced resolution

You can define an optional chain by placeing a question mark (?) after the optional value of a property, method, or subse cursor script.

Optional chain '?' Exclamation point (!) forces the expand method, property, subsection script optional chain
? Placed on optional values later called methods, properties, underseed scripts ! Placed on the optional value later calls the method, property, and the undersection script to force the value to expand
When optional nil outputs a more friendly error message Force an execution error when nil is optional

Use an exclamation point (!) Optional chain instance

class Person {
    var residence: Residence?
}

class Residence {
    var numberOfRooms = 1
}

let john = Person()

//将导致运行时错误
let roomCount = john.residence!.numberOfRooms

The output of the above program execution is:

fatal error: unexpectedly found nil while unwrapping an Optional value

If you want to use an exclamation point (!) to force resolution to obtain the value of this person's residence property, the numberOfRooms property value will throw a runtime error because there is no residence value available for resolution.

Use an exclamation point (!) Optional chain instance

class Person {
    var residence: Residence?
}

class Residence {
    var numberOfRooms = 1
}

let john = Person()

// 链接可选residence?属性,如果residence存在则取回numberOfRooms的值
if let roomCount = john.residence?.numberOfRooms {
    print("John 的房间号为 \(roomCount)。")
} else {
    print("不能查看房间号")
}

The output of the above program execution is:

不能查看房间号

Because this attempt to obtain the numberOfRooms operation is likely to fail, the optional chain returns the Int? type value, or "Optional Int". W hen the residence is empty (in the example above), selecting Int will be empty, so there will be an inability to access the HumberOfRooms.

Note that this is true even if the HumberOfRooms are non-optional Ints. A s long as the request is made through an optional chain, it means that at the end of the day the HumberOfRooms always return an Int?


Define model classes for optional chains

You can use an optional chain to call properties, methods, and undersemination scripts at multiple layers. This allows you to take advantage of the complex models between them to get the underlying properties and to check that such underlying properties can be obtained successfully.

Instance

Four model classes are defined, including multiple layers of optional chains:

class Person {
    var residence: Residence?
}

// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组
class Residence {
    var rooms = [Room]()
    var numberOfRooms: Int {
        return rooms.count
    }
    subscript(i: Int) -> Room {
        return rooms[i]
    }
    func printNumberOfRooms() {
        print("房间号为 \(numberOfRooms)")
    }
    var address: Address?
}

// Room 定义一个name属性和一个设定room名的初始化器
class Room {
    let name: String
    init(name: String) { self.name = name }
}

// 模型中的最终类叫做Address
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
        }
    }
}

The method is called through an optional chain

You can use an optional chain to call methods with optional values and check that the method call was successful. Even if this method does not have a return value, you can still use an optional chain to do so.

class Person {
    var residence: Residence?
}

// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组
class Residence {
    var rooms = [Room]()
    var numberOfRooms: Int {
        return rooms.count
    }
    subscript(i: Int) -> Room {
        return rooms[i]
    }
    func printNumberOfRooms() {
        print("房间号为 \(numberOfRooms)")
    }
    var address: Address?
}

// Room 定义一个name属性和一个设定room名的初始化器
class Room {
    let name: String
    init(name: String) { self.name = name }
}

// 模型中的最终类叫做Address
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
        }
    }
}

let john = Person()


if ((john.residence?.printNumberOfRooms()) != nil) {
    print("输出房间号")
} else {
    print("无法输出房间号")
}

The output of the above program execution is:

无法输出房间号

Use the if statement to check that the printNumberOfRooms method can be successfully called: if the method is successfully called through an optional chain, the implicit return value of printNumberOfRooms will be Void and, if not successful, nil.


Use an optional chain to call the underseed script

You can use an optional chain to try to get a value from the underseed script and check that the call to the underseed script was successful, however, you cannot set the underseed script with an optional chain.

Example 1

class Person {
    var residence: Residence?
}

// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组
class Residence {
    var rooms = [Room]()
    var numberOfRooms: Int {
        return rooms.count
    }
    subscript(i: Int) -> Room {
        return rooms[i]
    }
    func printNumberOfRooms() {
        print("房间号为 \(numberOfRooms)")
    }
    var address: Address?
}

// Room 定义一个name属性和一个设定room名的初始化器
class Room {
    let name: String
    init(name: String) { self.name = name }
}

// 模型中的最终类叫做Address
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
        }
    }
}

let john = Person()
if let firstRoomName = john.residence?[0].name {
    print("第一个房间名 \(firstRoomName).")
} else {
    print("无法检索到房间")
}

The output of the above program execution is:

无法检索到房间

The question mark of the optional chain in the underseed script call follows directly behind circname.print and before the parenthesis of the underseed script, because circname.print is the optional value that the optional chain is trying to obtain.

Example 2

If you create a Residence instance to john.residence in an instance, and you have one or more Room instances in his rooms array, you can use the optional chain to get the instances in the rooms array using the Residence substation script:

class Person {
    var residence: Residence?
}

// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组
class Residence {
    var rooms = [Room]()
    var numberOfRooms: Int {
        return rooms.count
    }
    subscript(i: Int) -> Room {
        return rooms[i]
    }
    func printNumberOfRooms() {
        print("房间号为 \(numberOfRooms)")
    }
    var address: Address?
}

// Room 定义一个name属性和一个设定room名的初始化器
class Room {
    let name: String
    init(name: String) { self.name = name }
}

// 模型中的最终类叫做Address
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
        }
    }
}

let john = Person()
let johnsHouse = Residence()
johnsHouse.rooms.append(Room(name: "客厅"))
johnsHouse.rooms.append(Room(name: "厨房"))
john.residence = johnsHouse

if let firstRoomName = john.residence?[0].name {
    print("第一个房间名为\(firstRoomName)")
} else {
    print("无法检索到房间")
}

The output of the above program execution is:

第一个房间名为客厅

Access the underration through an optional link call

With an optional link call, we can read or write the optional value with the underseed and determine whether the underseed call was successful.

Instance

class Person {
    var residence: Residence?
}

// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组
class Residence {
    var rooms = [Room]()
    var numberOfRooms: Int {
        return rooms.count
    }
    subscript(i: Int) -> Room {
        return rooms[i]
    }
    func printNumberOfRooms() {
        print("房间号为 \(numberOfRooms)")
    }
    var address: Address?
}

// Room 定义一个name属性和一个设定room名的初始化器
class Room {
    let name: String
    init(name: String) { self.name = name }
}

// 模型中的最终类叫做Address
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
        }
    }
}

let john = Person()

let johnsHouse = Residence()
johnsHouse.rooms.append(Room(name: "客厅"))
johnsHouse.rooms.append(Room(name: "厨房"))
john.residence = johnsHouse

if let firstRoomName = john.residence?[0].name {
    print("第一个房间名为\(firstRoomName)")
} else {
    print("无法检索到房间")
}

The output of the above program execution is:

第一个房间名为客厅

Access the tender of the optional type

If the undersection returns an empty type value, such as the key undersection of Dictionary in Swift. You can place a question mark after the closed parenthesis of the underlying to link the empty return value of the underlying:

var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
testScores["Dave"]?[0] = 91
testScores["Bev"]?[0]++
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 TestScores array that contains two pairs of key values, mapping the key of the String type to a shaping array.

This example uses an optional link call to set the first element in the "Dave" array to 91, the first element of the "Bev" array to 1, and then tries to set the first element in the "Brian" array to 72.

The first two calls were successful because these two keys exist. H owever, key "Brian" does not exist in the dictionary, so the third call fails.


Connect multi-layer links

You can connect multiple layers of optional chains together to extract lower-level property methods and undersemination scripts within the model. H owever, a multi-layer optional chain can no longer add more layers than the optional values that have been returned.

If you try to get an Int value through an optional chain, no matter how many layers of links are used, the int?? Similarly, if you try to get an Int?value through an optional chain, no matter how many layers of links are used, always int?.

Example 1

The following example attempts to get the street property of address in john's residence property. Two layers of optional chains are used here to contact the residence and address properties, both of which are optional types:

class Person {
    var residence: Residence?
}

// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组
class Residence {
    var rooms = [Room]()
    var numberOfRooms: Int {
        return rooms.count
    }
    subscript(i: Int) -> Room {
        return rooms[i]
    }
    func printNumberOfRooms() {
        print("房间号为 \(numberOfRooms)")
    }
    var address: Address?
}

// Room 定义一个name属性和一个设定room名的初始化器
class Room {
    let name: String
    init(name: String) { self.name = name }
}

// 模型中的最终类叫做Address
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
        }
    }
}

let john = Person()

if let johnsStreet = john.residence?.address?.street {
    print("John 的地址为 \(johnsStreet).")
} else {
    print("不能检索地址")
}

The output of the above program execution is:

不能检索地址

Example 2

If you set an instance for Address as the value of john.residence.address and an actual value for the street property of address, you can get this property value through multiple layers of optional chains.

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("房间号为 \(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) {
            return buildingNumber
        } else {
            return nil
        }
    }
}
let john = Person()
john.residence?[0] = Room(name: "浴室")

let johnsHouse = Residence()
johnsHouse.rooms.append(Room(name: "客厅"))
johnsHouse.rooms.append(Room(name: "厨房"))
john.residence = johnsHouse

if let firstRoomName = john.residence?[0].name {
    print("第一个房间是\(firstRoomName)")
} else {
    print("无法检索房间")
}

The output of the above examples is:

第一个房间是客厅

Link functions that return optional values

We can also call methods that return empty values through optional links, and we can continue to link optional values.

Instance

class Person {
    var residence: Residence?
}

// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组
class Residence {
    var rooms = [Room]()
    var numberOfRooms: Int {
        return rooms.count
    }
    subscript(i: Int) -> Room {
        return rooms[i]
    }
    func printNumberOfRooms() {
        print("房间号为 \(numberOfRooms)")
    }
    var address: Address?
}

// Room 定义一个name属性和一个设定room名的初始化器
class Room {
    let name: String
    init(name: String) { self.name = name }
}

// 模型中的最终类叫做Address
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
        }
    }
}

let john = Person()

if john.residence?.printNumberOfRooms() != nil {
    print("指定了房间号)")
}  else {
    print("未指定房间号")
}

The output of the above program execution is:

未指定房间号