Optional type What is an optional type
There are two possible types of data for an optional value type: A value, no value (nil). Note that you need to add a question mark (?) after the variable type. If int plus question mark (?), the variable is of type int. Question mark (?) is a flag of an optional type.
Optional values can be used if the value is determined
#import Foundationvarnilifnil{ println("not nil")}else{ println("nil")}
How do I get the values in an optional value?
Forced parsing
Note Add an exclamation mark (!) after an optional variable.
An exclamation mark is a flag that forces parsing.
#import Foundation//非nil情况var optValue:Int? = 3println(intValue) //会打印Optional(3)println//会打印3var intValue:Int = optValue!println(intValue)//可选类型的Int才能赋值为nil,普通的Int只能赋值整型varnil//var intValue2:Int = optValue1!//println(intValue2)
Note If you force resolve no values, you may run the error together. So it's best to add a judgment for nil.
#import Foundationvarnilifnil { println(optValue1!) }
Optional bindings
Add a temporary amount and assign an optional value to the temporary variable, judging by the if condition to get the value of the optional type
If the variable of an optional type has no value if the condition does not satisfy, if the optional type variable has a value, the value is obtained through the temporary variable
#import Foundationvarnilif let tempValue = optValue1 { println(tempValue) }
Swift Language-optional type