博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Optional Chaining as an Alternative to Forced Unwrapping
阅读量:5818 次
发布时间:2019-06-18

本文共 1500 字,大约阅读时间需要 5 分钟。

?与!的区别

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.

 

  1. let roomCount = john.residence!.numberOfRooms
  2. // this triggers a runtime error

Accessing Subscripts Through Optional Chaining

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

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:

  1. var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
  2. testScores["Dave"]?[0] = 91
  3. testScores["Bev"]?[0] += 1
  4. testScores["Brian"]?[0] = 72
  5. // the "Dave" array is now [91, 82, 84] and the "Bev" array is now [80, 94, 81]

转载地址:http://yswdx.baihongyu.com/

你可能感兴趣的文章
Leetcode-Database-176-Second Highest Salary-Easy(转)
查看>>
构建Docker Compose服务堆栈
查看>>
最小角回归 LARS算法包的用法以及模型参数的选择(R语言 )
查看>>
CentOS7下zip解压和unzip压缩文件
查看>>
Hadoop生态圈-Kafka常用命令总结
查看>>
如何基于Redis Replication设计并实现Redis-replicator?
查看>>
Linux 环境下 PHP 扩展的编译与安装 以 mysqli 为例
查看>>
laravel中 url() route() URL::asset()
查看>>
浮点数内存如何存储的
查看>>
贪吃蛇
查看>>
EventSystem
查看>>
用WINSOCK API实现同步非阻塞方式的网络通讯
查看>>
vue
查看>>
玩一玩博客,嘿嘿
查看>>
P1352 没有上司的舞会
查看>>
ios11文件夹
查看>>
【HLOJ 559】好朋友的题
查看>>
Electric Fence(皮克定理)
查看>>
【状压DP】【UVA11825】 Hackers' Crackdown
查看>>
nvl 在mysql中如何处理
查看>>