Let's start by looking at the following code:
- var N1: Int = Ten
- N1 = Nil//Compile error
- Let str: String = Nil//Compile error
int and string types cannot accept nil, but sometimes it is unavoidable that the program is copied to nil during the run , andSwift provides an optional type (optional) for each data type. That is, after a data type with a question mark (?) or exclamation point (!), modify the preceding example code:
- var n1:int? = 10
- N1 = Nil
- Let str:string! = Nil
int? and string! are both original type int and String optional types, they can accept nil.
Optional type value unpacking
What is the difference between a question mark (?) or an exclamation point (!) in an optional type? This is related to the "unpacking" (unwrapping) of the optional type, which is to turn the optionaltype into a normal type, and if we print a non-empty optional type value directly, the code is as follows:
- var n1:int? = 10
- Print (N1)
The result of the output is Optional (10), not 10. So trying to evaluate the expression n1+ 100 will compile error, the code is as follows:
- var n1:int? = 10
- Print (n1 + 100)//Compile error occurred
It is necessary to "disassemble" the optional type value.
"Unpacking" is divided into show unpacking and hidden unpacking.
an optional type declared with a question mark (?) that requires an exclamation point (!) when unpacking,which is called an explicit unpacking;
Anoptional type declared with an exclamation point (!) that can be split without using an exclamation point (!), which is called an implicit unpacking.
Take a look at the following code:
- var n1:int? = 10
- Print (n1! + 100)//Explicit unpacking
- var n2:int! = 100
- Print (n2 + 200)//implicit unpacking
Swift Optional Type-standby