Optional Chaining as an Alternative to Forced Unwrapping

來源:互聯網
上載者:User

標籤:rip   force   success   ted   ini   查詢   alt   for   access   

?與!的區別

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]

Optional Chaining as an Alternative to Forced Unwrapping

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.