Swift(十七、可选链)


1、Swift入门学习笔记(第一版),对Swift的基础知识点进行梳理总结。知识点一直在变,只是作为参考,以苹果官方文档为准~

2、在学习完基本的知识点以后会结合官方文档及相关资料,在此版本的基础上进行添加更改。


十七、可选链


1、写于前-概念梳理

1.1、可选类型使用时需要解包,解包时需要判断是否为nil,常用if语句判断,再去访问其属性或方法,否则会运行错误。当可选类型访问其属性还是可选时,即多层可选,那么if就显得比较麻烦。Swift提供了可选链(可空链式调用)

1.2、可空链式调用:一种可以请求和调用属性、方法和下标的过程,请求和调用目标可能为空。不为空调用成功,为空返回空(nil)。多个连续调用链接在一起,有任意一个结点为空(nil)将导致整个链调用失败。

1.3、多层链接:
a、访问的值不是可空,通过可选链将会放回可空值
b、访问的值已经是可空,通过可选链调用不会变的“更”可空
简言之:
a、可选链访问一个Int值,将返回Int?
b、可选链访问Int?值,你该不会变的更可空(仍然是可空)


通过拆分官方文档来说明:

class Person {
    var residence:Residence?
}

class Residence {
    var address:Address?
}

class Address {
    var buildingName:String?
    var buildingNumber:String?
    func buildingIdentifier() -> String? {
        if buildingName != nil {
            return buildingName
        }else if buildingNumber != nil {
            return buildingNumber
        }else {
            return nil
        }
    }
}

2、可空链式调用访问属性

let Zane = Person()
if let number = Zane.residence?.address?.buildingNumber {
    print("The buildingNumber of Zane's residence is \(number)")
}else {
    print("Unable to get the buildingNumber")
}

Output:

Unable to get the buildingNumber

可选链任意一个属性为空则返回nil


2.1、设置属性值
let myResidence = Residence()
Zane.residence = myResidence

let someAddress = Address()
someAddress.buildingNumber = "218"
Zane.residence?.address = someAddress

if let number = Zane.residence?.address?.buildingNumber {
    print("The buildingNumber of Zane's residence is \(number)")
}else {
    print("Unable to get the buildingNumber")
}

Output:

Output:
The buildingNumber of Zane's residence is 218

2.2、访问函数

通过可空链来调用AddressbuildingIdentifier()方法,返回的是String?类型,因此打印的是可选类型

print(Zane.residence?.address?.buildingIdentifier())

Output:

Optional("218")
if let buildingIdentifier = Zane.residence?.address?.buildingIdentifier() {
    print("Zane's building identifier is \(buildingIdentifier)")
}

Output:

Zane's building identifier is 218

3、下标可空值访问

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)")
    }
}

有一个存储Room类的数组,及房间数属性
通过下标读写数组元素

class Room {
    let name:String
    init(name:String) {
        self.name = name
    }
}

3.1、可选链调用方法
let Zane = Person()
if Zane.residence?.printNumberOfRooms() != nil {
    print("It was possible to print the number of rooms")
} else {
    print("Unable to print the number of rooms")
}

Output:

Unable to print the number of rooms

3.2、可选链访问下标

访问下标时,问号放在方括号前面
访问Zane.residencerooms数组中第一个房间名称

if let firstRoomName = Zane.residence?.rooms[0].name {
//if let firstRoomName = Zane.residence?[0].name {      //等同
    print("The first room name is \(firstRoomName).")
} else {
    print("Unable to get the first room name")
}

Output:

Unable to get the first room name

定义属性

let myResidence = Residence()
myResidence.rooms.append(Room(name: "Living Room"))
myResidence.rooms.append(Room(name: "BathRoom"))
Zane.residence = myResidence

if let firstRoomName = Zane.residence?.rooms[0].name {
    print("The first room name is \(firstRoomName).")
} else {
    print("Unable to get the first room name")
}

if Zane.residence?.printNumberOfRooms() != nil {
    print("It was possible to print the number of rooms")
} else {
    print("Unable to print the number of rooms")
}

Output:

The first room name is Living Room.
The number of rooms is 2
It was possible to print the number of rooms
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值