Swift Considerations (16)--optional chain

Source: Internet
Author: User

Optional Chain (Optional Chaining)We all know what "can be chosen" is. So what are the optional chains, for example, to explain:
struct myname{var name}
struct MyInfo {var myname:myname? = MyName ()}
Class MyClass {var structinstance:myinfo?

= MyInfo ()}
Here are two structs and one class, when. When this class is instantiated: var myinstance = MyClass () All of the optional properties are initialized because I write the default values.


if let name = myinstance.info?.myname?.name {(thanks to Swift Technical Exchange first platform (355277) group Friends week old Wet (974871365) indicates member name error)
If let name = myinstance.structinstance?. MyName?

. name {println (name)} else {println ("some info is nil")}
In the Scarlet Letter section, you can see that it is a series of optional values that are used.

This is called an optional chain. Here I also used a very early note mentioned in the IF let name = selectable {...} this syntax.
This is due to: in the optional chain, no matter what part of the optional parse failure (value nil), then the entire optional chain result is nil.
Of course, we may actually want to use the first link! "To allow an optional chain to return an exact value, rather than an optional value, for example: let name = Myinstance.info!. MyName!. Name but, in most cases, we don't know who's going to change the code. Who will change the implementation of a package. Assuming the wrong resolution of an optional value (a value of nil can be selected), then the consequences of only one, our program will be blown off ...

。 So, don't do this!

!。!


This chapter says something like this.

。。

As for what call function, use subscript, do not need to say again, logical ability normal human. will be used directly.



Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Swift Considerations (16)--optional chain

Related Article

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.