Selectable VALUES (Optional)
In OC, a class-type variable whose value can be either a valid object or nil. However, types such as int,double do not have nil values. For example, 32-bit int, which exceeds the maximum, OC is treated with nsnotfound instead of the nil value. Swift is more flexible than OC and supports all types of canon with nil values-selectable values (Optional)-directly at the syntactic level
How to use
With optional values, Swift provides a very concise way to add '? ' directly to the type. ', for example, to define an integer variable with an optional value:
var optionalinteger:int?
After you run Xcode playground, you can see the following effects:
Unpack (unwrapped)
Swift is a strongly typed language, so when the above optionalinteger is used, Swift does not want it to be an optional value, it must be an int, so it needs to be unpacked--simply understood, or transformed. Unpacking the operation, is also very simple, after the variable add '! ', such as:
var Normalinteger = optionalinteger! + 5
Value binding (binding)
The premise of unpacking is that you are sure that the variable is not nil, otherwise the forced unpacking is unsafe, Swfit provides another very concise syntax to check whether the pre-unpacking ratio is nil value-that is, value binding, again using Optionalinteger as an example:
If let Tempinteger = optionalinteger{ Normalinteger = tempinteger + 5 }else { //nil, do something}
Note that after the Tempinter is assigned, its value is not optional, but int, so no unpacking is required.
This article, refer to http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/
Swift::3:: Optional value