About optional Values optional
Unlike Oc,swift, the introduction of a new concept-an optional value-to understand the optional is essential for Swift's learning
Concept definition: A type that can have a value or can have no value (nil). In other words, it has two states: a value, no value (nil)
As I understand it, the optional value is a generic type with Boolean type Plus
How do you define an optional value?
The above code simply defines an optional value called Optionalvalue.
and the normal variable definition is not much different, the only difference is that there is a question mark,? is the packet of the ordinary value to be added after the type, that is, adding a question mark after a variable or constant's owning type can define it as a optional
Here I assign a value of 80, if not assigned, then it will be nil by default
Forced unpacking of optional values forced unwrapping
By adding a question mark after the type, you can change the variable or constant to an optional value, so what do you do in turn?
Swift provides an understanding of package operations by simply adding an exclamation mark after an optional value to force an optional value to unpack
It is said that the matter of coercion is not a good thing, so the question comes ...
In the above code, I created a optional variable, without assignment, which is nil by default
In the second business when I tried to unpack this optional, there was an error.
It turns out that the optional value of nil will be wrong when unpacking, and Apple's official document also emphasizes that if you are not 100% sure that this optional value has a value, then do not use forced unpacking
Optional value binding Optional binding
Now that the forced unpacking is an error when the optional value is nil, how do you read the data in the optional values?
Swift provides a more secure method-optional value binding optional bindings
The above is the official document provided by the usage, not very clear, the following is the code demo:
In the above code, I first defined an optional value string, assigned a value of 90, and then created a constant called Tempvalue with the optional binding. The IF statement determines whether or not to print this value based on whether Tempvalue has obtained a value from Optionalvalue, and the result of playground shows that the tempvalue is given a "90"
And when I do not assign value to the optional value, let it default to nil, print Tempvalue also no error, if Judge Tempvalue did not get the value from OptionValue, there is nothing to do, of course, will not error.
This is equivalent to finding an intermediary for an optional value, indirectly judging and reading the contents of the optional value, and in the case of not being nil when the current optional value is not determined, Apple officially recommends using this method to determine if the optional value is nil and try to get the data for the optional value.
Optional values for swift (optional)