Optional
is a major feature of Swift and the most confusing problem for swift beginners
- When a variable is defined, the variable is represented if it is specified
可选的
可以有一个指定类型的值,也可以是 nil
- When defining a variable, add one after the type
?
to indicate that the variable is optional
- The default value of a variable's optional option is
nil
- Constant options have no default values and are primarily used to set initial values in constructors for constants
//: num 可以是一个整数,也可以是 nil,注意如果为 nil,不能参与计算let num: Int? = 10
- If the Optional value is
nil
not allowed to participate in the calculation
- Only
解包(unwrap)
then can we participate in the calculation
- Add one after the variable to
!
forcibly unpack the package
Note: You must ensure that the value after unpacking is not nil, otherwise it will be an error
//: num 可以是一个整数,也可以是 nil,注意如果为 nil,不能参与计算let num: Int? = 10//: 如果 num 为 nil,使用 `!` 强行解包会报错let r1 = num! + 100//: 使用以下判断,当 num 为 nil 时,if 分支中的代码不会执行if let n = num { let r = n + 10}
Common errors
unexpectedly found nil while unwrapping an Optional value
Translation
在[解包]一个可选值时发现 nil
??
Operator
??
The operator can be used to determine 变量/常量
if the numeric value is nil
, or if it is, use the following value instead
- Simplifies code writing when using Swift development
??
- Equivalent to three mesh operation
let num: Int? = nillet r1 = (num ?? 0) + 10print(r1)
Swift's optional selectable values