敢说敢作敢为, 无怨无恨无悔。这篇文章主要讲述Optional Chaining as an Alternative to Forced Unwrapping相关的知识,希望能为你提供帮助。
?与!的区别
You specify optional chaining by placing a question mark (?
) after the optional value on which you wish to call a property, method or subscript if the optional is non-nil
. This is very similar to placing an exclamation mark (!
) after an optional value to force the unwrapping of its value. The main difference is that optional chaining fails gracefully when the optional is
nil
, whereas forced unwrapping triggers a runtime error when the optional is
nil
.
查询值为optional类型
To reflect the fact that optional chaining can be called on a
nil
value, the result of an optional chaining call is always an optional value,
Specifically, the result of an optional chaining call is of the same type as the expected return value, but wrapped in an optional.
let roomCount = john.residence!.numberOfRooms
// this triggers a runtime error
You can use optional chaining to try to retrieve and set a value from a subscript on an optional value, and to check whether that subscript call is successful.
Accessing Subscripts of Optional Type
【Optional Chaining as an Alternative to Forced Unwrapping】If a subscript returns a value of optional type—such as the key subscript of Swift’s
Dictionary
type—place a question mark
after
the subscript’s closing bracket to chain on its optional return value:var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
testScores["Dave"]?[0] = 91
testScores["Bev"]?[0] += 1
testScores["Brian"]?[0] = 72
// the "Dave" array is now [91, 82, 84] and the "Bev" array is now [80, 94, 81]
推荐阅读
- android -------- NDK 入门指南
- android解决AVD中文路径无法启动问题
- How to Restart Qt Application
- Android画图系列——自己定义View绘制基本图形
- android入门问题--R文件丢失
- Android View移动的六种方法
- MQ报错java.lang.IllegalStateException: Failed to load ApplicationContext
- mybatis 模糊查询 mapper.xml的写法(转)
- Android Studio NDK 新手教程--Java对象的传递与改动