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