zoukankan      html  css  js  c++  java
  • 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.

    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]
  • 相关阅读:
    6.Dump域内用户Hash姿势集合
    4.浅谈跨域劫持
    7. Smali基础语法总结
    7.linux安全基线加固
    12. git常用语法总结
    5.内网渗透之PTH&PTT&PTK
    4. 内网渗透之IPC$入侵
    1.我所了解的内网渗透
    34.不安全的HTTP
    2.内网渗透之端口转发
  • 原文地址:https://www.cnblogs.com/feng9exe/p/8718733.html
Copyright © 2011-2022 走看看