阅读 810

Swift 5.1 (15) - 可选链接

级别: ★☆☆☆☆
标签:「iOS」「Swift 」「可选链接」「多级可选」
作者: 沐灵洛
审校: QiShare团队


可选链接

可选链接:查询和调用当前可能为nil的可选项的属性,方法和下标的过程。若当前optional包含值,则属性,方法或下标调用成功;若optionalnil,则属性,方法或下标调用会返回nil。多个可选链接可以链在一起,如果链中的任何可选链接返回nil,则整个链都会正常失败。

可选链接作为强制解包的替代方法

可选链接表示:在要调用属性,方法或下标的可选项后放置?。与可选项后放置!进行强制解包相似,但主要区别在于使用?时,当可选项为nil,链接便会返回nil,来正常失败;若为!,可选项为nil时,强制解包会触发运行时错误。 即使要查询的属性,方法或下标返回的是非可选值,可选链接调用的结果也始终是可选的。

class Person {
    var residence: Residence?
}
class Residence {
    var numberOfRooms = 1
}
let john = Person()
//`!`方式访问属性
let roomCount = john.residence!.numberOfRooms
//`?`方式访问属性
if let roomCount = john.residence?.numberOfRooms {
    print("John's residence has \(roomCount) room(s).")
} else {
    print("Unable to retrieve the number of rooms.")
}
复制代码

定义模型类:

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 let buildingNumber = buildingNumber, let street = street {
            return "\(buildingNumber) \(street)"
        } else if buildingName != nil {
            return buildingName
        } else {
            return nil
        }
    }
}
复制代码

通过可选链接访问属性

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.")
}
//赋值
let someAddress = Address()
someAddress.buildingNumber = "29"
someAddress.street = "Acacia Road"
john.residence?.address = someAddress
复制代码

通过可选链接访问方法

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 room name is \(firstRoomName).")
} else {
    print("Unable to retrieve the first room name.")
}
//赋值
john.residence?[0] = Room(name: "Bathroom")
复制代码
访问可选类型的下标
var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
testScores["Dave"]?[0] = 91
testScores["Bev"]?[0] += 1
testScores["Brian"]?[0] = 72
//调用后: "Dave" : [91, 82, 84] , "Bev": [80, 94, 81]
复制代码

多级可选链接

多级可选链接:将多个级别的可选链接链接在一起。采用这种方式访问和调用属性,方法和下标时: 1.返回值不是可选的,也会因为可选链接而成为可选类型。 2.返回值本身是可选的,不会因为可选链接变得更加可选。

if let johnsStreet = john.residence?.address?.street {
    print("John's street name is \(johnsStreet).")
} else {
    print("Unable to retrieve the address.")
}
复制代码

####可选链接上有optional类型的返回值的方法

if let buildingIdentifier = john.residence?.address?.buildingIdentifier() {
    print("John's building identifier is \(buildingIdentifier).")
}
//方法的可选返回值后继续调用
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\".")
    }
}
复制代码

参考资料: swift 5.1官方编程指南


了解更多iOS及相关新技术,请关注我们的公众号:

image

可添加如下小编微信,并备注加入QiShare技术交流群,小编会邀请你加入《QiShare技术交流群》。

小编微信

关注我们的途径有:
QiShare(简书)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公众号)

推荐文章:
浅谈编译过程
深入理解HTTPS 浅谈 GPU 及 “App渲染流程”
iOS 查看及导出项目运行日志
Flutter Platform Channel 使用与源码分析
开发没切图怎么办?矢量图标(iconFont)上手指南
DarkMode、WKWebView、苹果登录是否必须适配?
奇舞团安卓团队——aTaller
奇舞周刊