Original articles, welcome reprint. Reprint Please specify: Dongsheng's Blog
Optional type:
Let's start by looking at the following code:
var Ten = nil // compile error = 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, and Swift provides an optional type (optional) for each data type, that is, a question mark (?) or exclamation point (!) after a data type. Modify the preceding example code:
var Ten = 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 optional type into a normal type, and if we print a non-empty optional type value directly, the code is as follows:
var Ten Print (n1)
The result of the output is optional (10), not 10. So trying to evaluate the expression N1 + 100 will cause a compile error, the code is as follows:
var Ten ) // 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;
An optional 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 ) var n2:int! = 100 print (N2 + 200 ) // implicit unpacking
Welcome to follow Dongsheng Sina Weibo @tony_ Dongsheng.
Learn about the latest technical articles, books, tutorials and information on the public platform of the smart Jie classroom
?
More Products iOS, Cocos, mobile design courses please pay attention to the official website of Chi Jie Classroom: http://www.zhijieketang.com
Luxgen Classroom Forum Website: http://51work6.com/forum.php
Swift 2.0 Study Notes (Day 27)--optional types