Apple提供了一个简洁的可选链接示例
class Person { var residence: Residence? } class Residence { var numberOfRooms = 1 } let john = Person() if let roomCount = john.residence?.numberOfRooms { println("John's residence has \(roomCount) room(s).") } else { println("Unable to retrieve the number of rooms.") }
想象一下尝试用一些算术运算来调整条件.这会导致编译器错误,因为模运算符不支持选项.
if john.residence?.numberOfRooms % 2 == 0 { // compiler error: Value of optional type Int? not unwrapped println("John has an even number of rooms") } else { println("John has an odd number of rooms") }
当然,您总是可以执行以下操作,但它缺乏可选链接的简单性和简洁性.
if let residence = john.residence { if residence.numberOfRooms % 2 == 0 { println("John has an even number of rooms") }else{ println("John has an odd number of rooms") } } else { println("John has an odd number of rooms") }
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。