Optional Chaining as an alternative to forced unwrapping

Source: Internet
Author: User

? And! The difference

You specify optional chaining by placing a question mark ( ? ) after the optional value on which we wish to call a prop Erty, method or subscript if the optional is non- nil . This was very similar to placing a exclamation mark () after a optional value to force the unwrapping of its ! value. The main difference is this optional chaining fails gracefully when nil the optional is, whereas forced unwrapping Trigg ERs a runtime error when the optional is nil .

Query value is optional type

To reflect the fact that optional chaining can being called on a nil value, the result of an optional chaining Always an optional value,

Specifically, the result of a optional chaining call is of the the same type as the expected return value 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 Wheth Er 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 in its optional return value:

    1. var testscores = [ "Dave": [86, 82, 84], "Bev": [ 94, 81]]
    2. testscores[ "Dave"]?[ 0] = 91
    3. < Span class= "VC" >testscores[ "Bev"]?[ 0] + = 1
    4. < Span class= "VC" >testscores[ "Brian"]?[ 0] = 72
    5. < span class= "C" >//the "Dave" Array is now [,, +] and the "Bev" array is now [+, 94, Bayi]

Optional Chaining as an alternative to forced unwrapping

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.