Use an optional value (optional) If the value may not exist, and the optional values are:
· There is a value that equals X
Or
· No value exists
Note:
The concept of an optional value in C and objective-c does not exist. The closest (concept) in objective-c (to an optional value) is a method that returns a value with an object, or a nil,nil that says "no valid object exists." However, this rule is only valid for objects-not valid for structs, base C types, or enumeration values. For these types, the Objective-c language method usually returns a special value, such as Nsnotfound, to indicate that the value does not exist. This policy assumes that the caller of the method knows whether to test that the return value is equal to a particular value, and remember to do this check. Swift's optional value allows you to indicate that no value exists for any type, and that you do not need to define special constants.
Here's an example. Swift's string type has a method named ToInt, which attempts to convert a string value to an INT value. However, not all strings can be converted to integers. The string "123" can be converted to a value of 123, while the string "Hello, World" obviously has no corresponding numeric value.
The following example attempts to convert a String to an Int using the ToInt method:
1 Let Possiblenumber (possibly number) = "123"
2 let Convertednumber (converted number) = Possiblenumber.toint ()
3//convertednumber is inferred as the "int?" type, or "optional int"
Because the ToInt method may fail to convert, it returns an optional int, not an int type. The optional int is written as int instead of Int. The question mark indicates that the value contained in the type is optional, that is, Int? May contain a value of an Int type, or it may not have any value. (it cannot contain other types of values, such as Bool values or String values, which are either Int or do not exist.) )
If statement and forced unpacking
You can use the IF statement to test whether an optional value contains a value. If there is, the evaluation returns TRUE, or false.
Once you have confirmed that an optional value does contain a value, you can access its internal values by adding an exclamation point (!) at the end of the optional value variable name. The exclamation point is clearly expressed: "I know that the optional value does exist, please use it (that value)!" "This operation is known as forcing a split on an optional value (FORCE-UNWRAP):
If Convertednumber (number converted) {
println ("\ (possiblenumber) integer value is \ (convertednumber!)")
} else {
println (" \ (Possiblenumber) cannot be converted to an integer ")
}
//Output" 123 integer value is 123 "
For more information about if statements, see Process Control.
Note:
Try to use! Access to an optional value that does not exist will be in run times wrong, in use! Make sure that the optional value does contain a value that is not nil before you forcibly split the package.
Optional value Binding
You can use an optional value binding (optional binding) to test whether an optional value contains a value and, if so, to split the value as a temporary constant or variable. An optional value binding can be used in conjunction with an if or a while statement, so that only one step is needed to check for the existence of a value, extract the value, and place it in a constant or variable. More information about if and while statements is mentioned in the Process Control chapter.
Optional value binding and if mixing can be this way:
1 if let Constantname = someoptional {
2 statements
3}
In the Possiblenumber example above, you can use optional value bindings instead of forced unpacking:
If Let Actualnumber = Possiblenumber.toint () {
println ("\ (possiblenumber) integer value is \ (actualnumber)")
} else {
println ("\ (Possiblenumber) cannot be converted to integer")
}
//Output "123 integer value is 123"
You can understand this:
"If the optional Int returned by Possiblenumber.toint () contains a value, create a new constant named Actualnumber and set the value of the constant to the value contained in the optional value. ”
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/extra/
If the conversion succeeds, the constant Actualnumber will be available for the first spoke statement of the IF statement. The constant is initialized with the value contained in the optional value, so the suffix is no longer needed! Access its value. In this case, the actualnumber is directly used to output the conversion results.
Constants and variables are available for optional value binding. If you need to work with actualnumber values in the first branch, you can overwrite the IF Var actualnumber so that the value of the optional value will be split as a variable.
Nil
To set an optional variable to a null value (a state that does not have a value or a value that does not exist, valueless), you can assign it a special value nil:
1 var serverresponsecode (Server Status code): Int? = 404
2//The Server status code contains an actual Int value: 404
3 serverresponsecode= Nil
4//Server status code does not now contain any value
Note:
Nil cannot be used for constants or variables that are not optional values. If a constant or variable in your code requires a special case where the fitting value does not exist, be sure to declare it as the applicable optional value type.
If you define an optional value that does not provide a default value, the constant or variable is automatically set to nil:
1 var surveyanswer:string?
2//Surveyanswer is automatically set to nil
Note:
Swift's nil is different from Objective-c's nil. The nil of objective-c is a pointer to an object that does not exist, and Swift's nil is not a pointer-it is a special type that represents a value that does not exist. Optional values of any type can be assigned to nil, not limited to object types.
Implicit unpacking of optional values
As mentioned above, an optional value is a constant or variable that allows a value not to exist. You can test whether an optional value has a value through an if statement, or you can use an optional value binding to split the package conditionally and access its value if the value of the optional value exists.
Sometimes, according to the program structure, an optional value must exist after the first assignment. At this point, you can not detect and extract the value of the optional value every time you access it, because it is safe to assume that it must have a value at that time.
These optional values can be defined as optional values for an implicit unpacking (implicitly unwrapped optional). You can use an exclamation point (string!) instead of a question mark (String?) by following the name of the type you want to mark as optional. The way to write an implicit unpacking optional value.
An optional value for an implicit unpacking confirms the existence of values after the first definition of an optional value, which can be explicitly (definitely) used at any time thereafter. Implicit unpacking optional values in Swift are primarily applied to class initialization, as detailed in the optional attributes of external references and implicit unpacking (to be translated).
An optional value for an implicit unpacking is a normal optional value in the running environment, but it can be used like a non optional value, without unpacking on each access. The following example shows the behavior difference between an optional string and an optional string for an implicit unpacking:
Let possiblestring (Possible strings): string? = "an optional String. (an optional string) "
println (possiblestring!)//when accessing its value needs to add an exclamation
//output" optional string. "Let
assumedstring (assumed string): string! = "An implicitly unwraped optional String. An optional String (implicitly stirng) "
println (assumedstring)//that accesses its value without an exclamation//
output" implicit unpacking. "
Optionally, the optional value of an implicit unpacking gives the optional value the right to automatically split the package when it is used (that is, you do not need to manually disassemble the package again). You do not have to add an exclamation point after the name each time you use an optional value, simply by adding an exclamation point after the optional value type when you declare it.
Note: If you try to access an optional value of an implicit unpacking before the value exists (no implicit unpacking is possible if no value exists), the runtime will make an error. The results are referenced the same as if the normal optional value has not been assigned a value directly with an exclamation point.
An optional value for an implicit unpacking can also be used as a normal optional value to check for the existence of a value:
1 if assumedstring {
2 println (assumedstring)
3}
4//Output "an implicitly unwraped optional String. (optional stirng of an implicit unpacking) "
Optional values for implicit unpacking can also be used with optional value bindings, a single statement to complete the check value and to split the package:
1 if let definitestring (definitely a string) = Assumedstring (assumed to be a string) {
2 println (definitestring)
3}
4//output "optional String for an implicit unpacking. "
Note:
Optional values for implicit unpacking should not be used when a variable may become nil in subsequent procedures. If you need to check the nil value in the variable declaration cycle, be sure to use the normal amount of optional type.
Author: cnblogs Joe.huang