fengsh998 Original address:http://blog.csdn.net/fengsh998/article/details/28904115 Reprint Please indicate the source Suppose that the article is helpful to you. Please support me by leaving a message or following the public account fengsh998 , thank you.
Optional type, implicitly selectable type
In Swift. The source of an optional type is an enumerated type. There are two types of none and some. In fact, the so-called nil is optional.none, non-nil is optional.some, and then through the Some (T) wrapping (Wrap) The original value, which is why in the use of optional to unpack (from the enum to take out the original value) reason, It is also the reason that playground will display the optional value as a similar {Some "Hello World"}. Here is the definition of enum optional:
Enum optional<t>: Logicvalue, reflectable {case- None case Some (T) init () init (_ Some:t) // /Allow with in a Boolean context. Func getlogicvalue () Bool// Haskell ' s Fmap, which was mis-named func map<u> (f: (T)-U)-u? Func getmirror ()-Mirror}
Syntax use "? " operator and "! " Number operator
such as: "var optionalstring:string? = " Hello "
Optionalstring = Nil
var optionalname:string? = "John Appleseed"
var greeting = "Hello!"
If let name = optionalname {
Greeting = "Hello, \ (name)"
}”
Let's see what happens when we change optionalname to nil. According to the understanding, should be? = After is an optional value. That is, when our variable is nil. What do you suppose here? = operation, will it be used? = The value after is the default value, not nil. If this is an environment, verify it.
Verified by:
Execute separately:
var optional:string?= "OK good";//note there is a space between the = sign and the last letter cannot have a space println (optional)
The output is:
OK good
And
var optional:string?//note? Is there a space between the = sign?Number close to the last letter cannot have a space println (optional)
The output is:
Nil
Take a look. , the official interpretation of the implicit unpacking: mainly used in a variable/constant after the definition of the moment after the value of the situation must exist.
This is primarily used during the initialization of a class.
Official Wind Example:
Let possiblestring:string? = "An optional string." println (possiblestring!)//requires an exclamation mark to access its value//prints "an optional string." Let assumedstring:string! = "An implicitly unwrapped optional string." println (assumedstring)//No exclamation mark is needed to access its value
Actually speaking, you follow this example of execution, and really do not see anything, there is no conclusion. So I myself Z Grind, try to understand an English translation. Practice yourself again.
The following conclusions are drawn.
var optionvariables:string? ? The syntactic sugar equivalent to the following notation//var optionvariables:optional<int> let value = Optionvariables?. HashValue/* Optionvariables is an optional type of string. Suppose Optionvariables is nil. Then HashValue also for nil to assume that Optionvariables is not nil,hashvalue is the hash value of the strvalue string here we see?Two usage scenarios: 1. Declare the optional value variable 2. Used in the optional value operation, used to infer whether or not to respond to the following operation.////For an optional type variable, you cannot manipulate it directly. Otherwise it will error//let Hashval = optionvariables.hashvalue//' String?
' does not has a member named ' HashValue '//So to access the value of the need to unpack, unpacking there are two//first: using if let/var xxx = if let HV = optionvariables {//run OK; }//Another: use! let HV = optionvariables!. HashValue//here! "I'm sure the strvalue here must be non-nil, call it." For instance, if Optionvariables {let HASHV = optionvariables!. HashValue}//{} in the optionvariables must be non-nil, so you can directly add!, Force unpacking (unwrap) and perform the following actions
Where is the variable or constant added?
is an optional variable/optional constant
Where a variable or constant is added! is implicitly optional variable/constant, which is a bit difficult to understand, first the variable or constant satisfies the optional type. It is mainly used as a generic variable/constant, and does not need to be validated every time for a value.
Note: Assuming an optional type of implicit unpacking does not include an actual value, an access to it throws an execution-time error. Add after the variable/constant name!
The same is true of the situation.
var possiblestring:string?= "An optional string." possiblestring = nil println (possiblestring)//possiblestring is an optional variable. Need to use! The value of the interview
Analysis: First possiblestring with the back? Note this is an optional. At the same time, add Var to the variable, so this is an optional type of variable. The optional value is "an optional string." Again, after the execution of println, it is possible to see the output as an optional string. This is very obvious. Let's take a look at the println. Change this sentence to (that is, add one after the optional variable!). )
<span style= "FONT-SIZE:18PX;" >PRINTLN (possiblestring!)//possiblestring as an optional variable, need to use! The value of the visit </span>
The result here is the same as no add! The output is an optional string.
OK, here's the point now, it's a very critical test. Put possiblestring = nil This gaze let go of the movement, and then take a look at the println belt! and without! The situation:
Situation one: not with! Number. The output is nil.
<span style= "FONT-SIZE:18PX;" > var possiblestring:string?= "An optional string." possiblestring = nil println (possiblestring) </span>
case Two: Take a look again!
<span style= "FONT-SIZE:18PX;" > var possiblestring:string? = "an optional String." possiblestring = nil println (possiblestring!)//possiblestring is an optional variable. Need to use! The value of the visit </span>
Then execute to this sentence println will crash.
Will report
Fatal Error:can ' t unwrap Optional.none
error.
In the case of a moment. Why not error, is because this is an optional variable when the variable is nil, the active verification of whether there is an optional value, there is the use of optional values, in case two, plus! Access to the possiblestring variable. But since possiblestring is set to nil (equivalent to Var possiblestring:string?) It does not include an actual value, so throw an exception. The same is true for the following use! The same way:
<span style= "FONT-SIZE:18PX;" > var assumedstring:string! = "An implicitly unwrapped optional String." assumedstring = nil println (assumedstring!) </span>
same report:
fatal Error:can ' t unwrap optional.none
If you define an optional type and do not give the initial value, it is set to nil by default.
var surveyanswer:string?
At the beginning of their own initiative set to nil
Note: Swift's nil differs from nil in object-c. In Object-c, nil is a pointer to an object that does not exist.
In Swift. Nil is not a pointer but a null value of a specific type. No matter what type of optional variable can be set to nil, not just pointers.
The declaration of the variable/constant in Swift must have an initial value, otherwise it should be declared as selectable.
That is, Var Btn:uibutton this is a compile error. These must be initialized with the following example:
var btn2: UIButton = UIButton()
or use? And! to constrain.
Therefore, it is often declared that optional or implicit optional variables such as:
var Btn:uibutton? Default BTN = Nil
var edt:uitextfield! Default EDT = Nil
As for when to use?
Under what circumstances use! To constrain variables, I haven't figured out the true truth.
So help you understand by using your own several validations.
<span Style= "FONT-SIZE:18PX;" > var btn:uibutton? Default btn = nil var Btn2:uibutton = UIButton ()//default instantiation of an object Var btn3:uibutton! Default BTN = nil//var Btn4:uibutton//Compile time error requires initialization operation//Execution error fatal Error:can ' t unwrap Optional.none due to btn = Nil btn!. Tintcolor = Uicolor.blackcolor () btn!. Imageedgeinsets = Uiedgeinsets (top:1,left:2,bottom:3,right:4) btn!. frame = CGRectMake (0,0,50,40)//Perform normal Btn2.tintcolor = Uicolor.blackcolor () btn2.imageedgeinse ts = uiedgeinsets (top:1,left:2,bottom:3,right:4) btn2.frame = CGRectMake (0,0,50,40)//execution will error fatal err Or:can ' t unwrap optional.none for btn3 = nil Btn3.tintcolor = Uicolor.blackcolor () btn3.imageedgeinsets = uied Geinsets (top:1,left:2,bottom:3,right:4) btn3.frame = CGRectMake (0,0,50,40) </span>
In order to implement the period therefore not crash can be changed for example the following:
<span style= "FONT-SIZE:18PX;" > var btn:uibutton?Default btn = nil var Btn2:uibutton = UIButton ()//default instantiation of an object Var btn3:uibutton! Default BTN = nil//execution will error fatal Error:can ' t unwrap optional.none because BTN = nil if var tmpbtn = btn {btn!. Tintcolor = Uicolor.blackcolor () btn!. Imageedgeinsets = Uiedgeinsets (top:1,left:2,bottom:3,right:4) btn!. frame = CGRectMake (0,0,50,40)}//Perform normal Btn2.tintcolor = Uicolor.blackcolor () btn2.imag Eedgeinsets = Uiedgeinsets (top:1,left:2,bottom:3,right:4) btn2.frame = CGRectMake (0,0,50,40)//Execution error Fatal Error:can ' t unwrap optional.none because btn3 = nil if var tmpbtn = btn {Btn3.tintcolor = Uicolo R.blackcolor () Btn3.imageedgeinsets = Uiedgeinsets (top:1,left:2,bottom:3,right:4) btn3.frame = CGRec Tmake (0,0,50,40)}</span>
or
<span style= "FONT-SIZE:18PX;" > var btn:uibutton? Default btn = nil var Btn2:uibutton = UIButton ()//default instantiation of an object Var btn3:uibutton! Default BTN = nil//execution will error fatal Error:can ' t unwrap optional.none because BTN = nil if btn { btn!. Tintcolor = Uicolor.blackcolor () btn!. Imageedgeinsets = Uiedgeinsets (top:1,left:2,bottom:3,right:4) btn!. frame = CGRectMake (0,0,50,40)}//Perform normal Btn2.tintcolor = Uicolor.blackcolor () btn2.imag Eedgeinsets = Uiedgeinsets (top:1,left:2,bottom:3,right:4) btn2.frame = CGRectMake (0,0,50,40)//Execution error Fatal Error:can ' t unwrap optional.none because BTN3 = nil if btn3 {btn3.tintcolor = Uicolor.blackcolor () Btn3.imageedgeinsets = Uiedgeinsets (top:1,left:2,bottom:3,right:4) btn3.frame = CGRectMake (0,0,50 ,}</span>)
Note: Suppose there is a possibility that an optional type has no value. You should not use unpacked (implicit) optional types. In this case, be sure to use the normal optional type.
This is what I personally understand, such as Var view:uiview. can be set to var when view = Nil is not available in my entire application or in the entire class. view:uiview! Otherwise it can be declared to Var view:uiview?
copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Initial Swift Language learning Note 2 (optional type?) and an implicitly selectable type! )