Swift Novice Tutorial 12-optional chain

Source: Internet
Author: User

Optional chain

Original blog, reproduced please indicate the source
My blog Address

Http://blog.csdn.net/hello_hwc
An optional chain provides an optional way to access an object's properties, methods, subscript scripts, and the return value of an optional chain must be an optional type.
Merit: Substitution forced parsing (symbol!) , such as instance.location!. y), resulting in an execution-time error due to forced resolution of nil values
My experience: For a chain call, for example instance. Frame.origin.x, such as the very long call, the part that may be nil plus?

For example, frame and origin may be nil. Then use instance. Frame?. Origin?. X

Optional chain features: In the middle there is an optional value of nil, then the entire optional chain is invalidated. return Nil

A simple example is clear.

Class A{var vara:b?

}class B{var varb:c?

var varbarray = [D] () subscript (index:int)->d? {if (Index < varbarray.count) {return Varbarray[index]}else{return nil}}} Class C{var varc:string = "from C" func Printc () {println (VARC)}}class d{var vard1:int = 10var vard2:e = E ()} class E{func P Rinte () {println ("from E")}}var instance = A ()


I. Calling properties through an optional chain
Note: Because you return an optional type, you use the if let sentence to parse implicitly
If let temp = Instance.vara?. Varb?. Varc{println (temp)}

second, call the method through the optional chain
Instance.vara?. Varb?. PRINTC ()


Iii. calling subscript script through an optional chain
If let temp = Instance.vara?

[5]?. Vard1{println (temp)}


Explain why it's so used here.

Instance.vara? [5] An optional link is used to access the subscript script. Return d?, and then on the optional link to the returned d? Instance.vara? [5]?. VarD1

Four, long optional chain call

Instance.vara? [5]?. Vard2.printe ()

Swift Novice Tutorial 12-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.