An in-depth analysis of the optional chain _swift in Swift language programming

Source: Internet
Author: User
Tags access properties

The process of querying, invoking properties, subscripts, and methods on an optional possibly ' nil ' is defined as an optional chain. Optional chain returns two values

If the optional contains a value and then calls its associated properties, method and subscript return values

If optionally contains a "nil" value, all the associated properties, methods, and subscripts return nil

Because of a variety of query methods, attributes and subscript faults are grouped together, and a chain will affect the entire chain, resulting in a ' nil ' value.

Optional chains as an alternative to forced solution packages
optional chain and optional value specify "?" Invokes a property, method, or subscript when an optional value returns some values.

Program for optional chain '! '

Copy Code code as follows:

Class Electionpoll {
var candidate:pollbooth?
}
Class Pollbooth {
var name = "MP"
}

Let cand = Electionpoll ()

Let Candname = cand.candidate!. Name



When we use playground to run the above program, we get the following results.


Fatal error:unexpectedly found nil while unwrapping a Optional value 0 Swift 0x0000000103410b68 Llvm::sys::P rintstack Trace (__sfile*) + 1 Swift 0x0000000103411054 signalhandler (int) + 452 2 Libsystem_platform.dylib 0x00007fff9176af1a _ Sigtramp + 3 Libsystem_platform.dylib 0x000000000000000b _sigtramp + 1854492939 4 libsystem_platform.dylib 0x000000010  74a0214 _sigtramp + 1976783636 5 Swift 0x0000000102a85c39 llvm::jit::runfunction (llvm::function*, Std::__1::vector > const&) + 329 6 Swift 0x0000000102d320b3 Llvm::executionengine::runfunctionasmain (llvm::function*, std::__1::  Vector, Std::__1::allocator, std::__1::allocator, Std::__1::allocator > > > Const&, char const* const*) + 1523 7 Swift 0x000000010296e6ba swift::runimmediately (swift::compilerinstance&, Std::__1::vector, Std::__1:: Allocator, Std::__1::allocator, Std::__1::allocator > > > Const&, Swift::irgenoptions&, Swift:: Siloptions const&) + 1066 8 Swift 0x000000010275764b Frontend_main (Llvm::arrayref, Char const*, void*) + 5275 9 Swift 0x0000000102754a6d main + 1677 Libdy Ld.dylib 0x00007fff8bb9e5c9 start + 1 libdyld.dylib 0x000000000000000c start + 1950751300 Stack dump:0. Program Argu ments:/applications/xcode.app/contents/developer/toolchains/xcodedefault.xctoolchain/usr/bin/swift-frontend- Interpret--target x86_64-apple-darwin14.0.0-target-cpu core2-sdk/applications/xcode.app/contents/developer/ Platforms/macosx.platform/developer/sdks/macosx10.10.sdk-module-name main/bin/sh:line 47:15672 done cat << ' SW
 IFT ' Import Foundation

The above program declares "election poll" as the class name and includes "candidate" as the membership function. Subclasses are declared as "poll booth" and "name" as membership functions that are initialized to ' MP '. Calls to superclass are created by creating an instance of "Cand" optional Initialization "!". Because these values are not declared in its base class, the "nil" value is stored to return a fatal error by forcing the unpack process.

Program for optional chain '? '

Copy Code code as follows:

Class Electionpoll {
var candidate:pollbooth?
}
Class Pollbooth {
var name = "MP"
}

Let cand = Electionpoll ()

If let Candname = Cand.candidate? Name {
println ("Candidate name is \ (candname)")
}
else {
println ("Candidate name cannot be retreived")
}



When we use playground to run the above program, we get the following results.

Candidate name cannot be retreived

The above program declares "election poll" as the class name and includes "candidate" as the membership function. Subclasses are declared as "poll booth" and "name" as membership functions that are initialized to ' MP '. The invocation of a superclass is by creating an instance of "Cand" optionally initializing "?". Because the value of the base class ' nil ' is not declared to be stored and printed on the console, it is handled by another program block.

To define optional links and access properties for model classes
The Swift language also provides an optional chain concept that declares model classes for multiple subclasses. This concept will be useful for defining complex model and access attributes, methods, and subscript child properties.

Copy Code code as follows:



Class Rectangle {


var print:circle?


}

Class Circle {
var area = [radius] ()
var Cprint:int {
Return Area.count
}

Subscript (i:int)-> radius {
get {
return Area[i]
}
set {
Area[i] = newvalue
}
}
Func Circleprint () {
println ("The number of rooms is \ (cprint)")
}
var rectarea:circumference?
}

Class Radius {
Let radiusname:string
Init (radiusname:string) {self.radiusname = Radiusname}
}

Class Circumference {
var circumname:string?
var circumnumber:string?
var street:string?

Func buildingidentifier ()-> String? {
If Circumname!= Nil {
Return Circumname
else if Circumnumber!= nil {
Return Circumnumber
} else {
return Nil
}
}
}

Let Rectname = Rectangle ()

If let Rectarea = Rectname.print? Cprint {
println ("area of rectangle is \ (rectarea)")
} else {
println ("Rectangle area isn't specified")
}




When we use playground to run the above program, we get the following results.


Rectangle area isn't specified



Calling methods through an optional chain

Copy Code code as follows:



Class Rectangle {


var print:circle?


}


Class Circle {


var area = [radius] ()


var Cprint:int {


Return Area.count


}


Subscript (i:int)-> radius {


get {


return Area[i]


}


set {


Area[i] = newvalue


}


}





Func Circleprint () {


println ("Area of Circle is: \ (cprint)")


}


var rectarea:circumference?


}

Class Radius {
Let radiusname:string
Init (radiusname:string) {self.radiusname = Radiusname}
}

Class Circumference {
var circumname:string?
var circumnumber:string?
var circumarea:string?

Func buildingidentifier ()-> String? {
If Circumname!= Nil {
Return Circumname
else if Circumnumber!= nil {
Return Circumnumber
} else {
return Nil
}
}
}

Let Circname = Rectangle ()

If Circname.print? Circleprint ()!= Nil {
println ("The circle is specified)")
} else {
println ("Area of Circle isn't specified")
}




When we use playground to run the above program, we get the following results.

Area of circle are not specified

The function Circleprint () is declared in the circle () subclass by creating an instance called "Circname". function returns a value that returns some user-defined print information if it contains a certain value. Otherwise it will be checked by the statement ' if Circname.print? Circleprint ()!= nil "

Subscript access through an optional chain
optional chain sets and retrieves the subscript value to verify that the subscript is invoked to return a value. '? ' is placed in the subscript bracket to access a specific subscript optional value.

Program 1

Copy Code code as follows:



Class Rectangle {


var print:circle?


}

Class Circle {
var area = [radius] ()
var Cprint:int {
Return Area.count
}

Subscript (i:int)-> radius {
get {
return Area[i]
}

set {
Area[i] = newvalue
}
}
Func Circleprint () {
println ("The number of rooms is \ (cprint)")
}
var rectarea:circumference?
}


Class Radius {
Let radiusname:string
Init (radiusname:string) {self.radiusname = Radiusname}
}

Class Circumference {
var circumname:string?
var circumnumber:string?
var circumarea:string?

Func buildingidentifier ()-> String? {
If Circumname!= Nil {
Return Circumname
else if Circumnumber!= nil {
Return Circumnumber
} else {
return Nil
}
}
}


Let Circname = Rectangle ()

If let Radiusname = Circname.print? [0].radiusname {
println ("The room name is \ \ radiusname.")
} else {
println ("Radius is not specified.")
}




When we use playground to run the above program, we get the following results.

The Radius is not specified.

The instance value of the member function "Radiusname" is not specified in the above program. Therefore, a program calling the function returns a unique content that returns part of the value that must be defined for a particular member function.

Program 2

Copy Code code as follows:



Class Rectangle {


var print:circle?


}

Class Circle {
var area = [radius] ()
var Cprint:int {
Return Area.count
}

Subscript (i:int)-> radius {
get {
return Area[i]
}
set {
Area[i] = newvalue
}
}
Func Circleprint () {
println ("The number of rooms is \ (cprint)")
}
var rectarea:circumference?
}

Class Radius {
Let radiusname:string
Init (radiusname:string) {self.radiusname = Radiusname}
}

Class Circumference {
var circumname:string?
var circumnumber:string?
var circumarea:string?

Func buildingidentifier ()-> String? {
If Circumname!= Nil {
Return Circumname
else if Circumnumber!= nil {
Return Circumnumber
} else {
return Nil
}
}
}

Let Circname = Rectangle ()
Circname.print? [0] = radius (radiusname: "diameter")

Let printing = Circle ()
Printing.area.append (RADIUS (radiusname: "Units"))
Printing.area.append (RADIUS (radiusname: "Meter"))
Circname.print = Printing

If let Radiusname = Circname.print? [0].radiusname {
println ("Radius is measured in \ (radiusname).")
} else {
println ("Radius is not specified.")
}




When we use playground to run the above program, we get the following results.

Radius is measured in Units.

The above program is specified as the instance value of the member function "Radiusname". Therefore, the program now calls the function to have the return value.

Optional type access subscript

Copy Code code as follows:



Class Rectangle {


var print:circle?


}

Class Circle {
var area = [radius] ()
var Cprint:int {
Return Area.count
}

Subscript (i:int)-> radius {
get {
return Area[i]
}
set {
Area[i] = newvalue
}
}

Func Circleprint () {
println ("The number of rooms is \ (cprint)")
}
var rectarea:circumference?
}


Class Radius {
Let radiusname:string
Init (radiusname:string) {self.radiusname = Radiusname}
}

Class Circumference {
var circumname:string?
var circumnumber:string?
var circumarea:string?

Func buildingidentifier ()-> String? {
If Circumname!= Nil {
Return Circumname
else if Circumnumber!= nil {
Return Circumnumber
} else {
return Nil
}
}
}

Let Circname = Rectangle ()
Circname.print? [0] = radius (radiusname: "diameter")

Let printing = Circle ()
Printing.area.append (RADIUS (radiusname: "Units"))
Printing.area.append (RADIUS (radiusname: "Meter"))
Circname.print = Printing

var area = [Radius]: [90, 45, 56], [Circle]:
area["Radius"]? [1] = 78
area["Circle"]? [1]--

println (area["Radius"]?[ 0])
println (area["Radius"]?[ 1])
println (area["Radius"]?[ 2])
println (area["Radius"]?[ 3])


println (area["Circle"]?[ 0])
println (area["Circle"]?[ 1])
println (area["Circle"]?[ 2])




When we use playground to run the above program, we get the following results.

Optional (m)
Optional (Optional)
Optional (a)
Optional (
Optional
) Optional (56)

An optional value for subscript can be accessed by reference to its subscript value. It can be accessed as subscript[0], subscript[1] and so on. The default value subscript for RADIUS is first specified as [35,45,78,101] and circle[90,45,56]. The subscript value is then radius[0] to 78, as well as the circle[1]〜45.

Multiple layers of link chains
multiple subclasses can also be contacted by an optional link by virtue of their superclass methods, attributes, and subscripts.

Optional multiple links can be linked:

If the retrieval type is not optional, the optional chain returns an optional value. For example, if a string passes through an optional chain, it returns a string? Value

Copy Code code as follows:



Class Rectangle {


var print:circle?


}

Class Circle {
var area = [radius] ()
var Cprint:int {
Return Area.count
}
Subscript (i:int)-> radius {
get {
return Area[i]
}
set {
Area[i] = newvalue
}
}
Func Circleprint () {
println ("The number of rooms is \ (cprint)")
}
var rectarea:circumference?
}


Class Radius {
Let radiusname:string
Init (radiusname:string) {self.radiusname = Radiusname}
}

Class Circumference {
var circumname:string?
var circumnumber:string?
var circumarea:string?

Func buildingidentifier ()-> String? {
If Circumname!= Nil {
Return Circumname
else if Circumnumber!= nil {
Return Circumnumber
} else {
return Nil
}
}
}


Let Circname = Rectangle ()

If let Radiusname = Circname.print? [0].radiusname {
println ("The room name is \ \ radiusname.")
} else {
println ("Radius is not specified.")
}




When we use playground to run the above program, we get the following results.

The Radius is not specified.

The instance value for the subordinate function "Radiusname" is not specified in the above program. Therefore, the program calls the function to return the unique content, and we must define a specific subordinate of the return value as part of the function value.

If the retrieval is already optional, the optional chain will also return an optional value. For example, what if the string? An optional chain will also access the return string? value.

Copy Code code as follows:



Class Rectangle {


var print:circle?


}

Class Circle {
var area = [radius] ()
var Cprint:int {
Return Area.count
}
Subscript (i:int)-> radius {
get {
return Area[i]
}
set {
Area[i] = newvalue
}
}
Func Circleprint () {
println ("The number of rooms is \ (cprint)")
}
var rectarea:circumference?
}


Class Radius {
Let radiusname:string
Init (radiusname:string) {self.radiusname = Radiusname}
}

Class Circumference {
var circumname:string?
var circumnumber:string?
var circumarea:string?

Func buildingidentifier ()-> String? {
If Circumname!= Nil {
Return Circumname
else if Circumnumber!= nil {
Return Circumnumber
} else {
return Nil
}
}
}


Let Circname = Rectangle ()

If let Radiusname = Circname.print? [0].radiusname {
println ("The room name is \ \ radiusname.")
} else {
println ("Radius is not specified.")
}




When we use playground to run the above program, we get the following results.

Radius is measured in Units.

The above program is designated as an instance value of the subordinate function "Radiusname". Therefore, the program calls the function to return a value.

Method optional return value on chain
An optional chain is used to define methods to access subclasses.

Copy Code code as follows:



Class Rectangle {


var print:circle?


}

Class Circle {
var area = [radius] ()
var Cprint:int {
Return Area.count
}

Subscript (i:int)-> radius {
get {
return Area[i]
}
set {
Area[i] = newvalue
}
}
Func Circleprint () {
println ("The number of rooms is \ (cprint)")
}
var rectarea:circumference?
}

Class Radius {
Let radiusname:string
Init (radiusname:string) {self.radiusname = Radiusname}
}

Class Circumference {
var circumname:string?
var circumnumber:string?
var circumarea:string?

Func buildingidentifier ()-> String? {
If Circumname!= Nil {
Return Circumname
else if Circumnumber!= nil {
Return Circumnumber
} else {
return Nil
}
}
}

Let Circname = Rectangle ()
Circname.print? [0] = radius (radiusname: "diameter")

Let printing = Circle ()
Printing.area.append (RADIUS (radiusname: "Units"))
Printing.area.append (RADIUS (radiusname: "Meter"))
Circname.print = Printing

If let Radiusname = Circname.print? [0].radiusname {
println ("Radius is measured in \ (radiusname).")
} else {
println ("Radius is not specified.")
}




When we use playground to run the above program, we get the following results.

Area of circle are not specified

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.