Dmi*_*try 3 null optional swift
Swift允许声明变量但不初始化.如何检查变量是否未在Swift中初始化?
class myClass {}
var classVariable: myClass // a variable of class type - not initialized and no errors!
//if classVariable == nil {} // doesn't work - so, how can I check it?
Run Code Online (Sandbox Code Playgroud)
and*_*n22 12
你是对的 - 你可能无法比较非可选变量nil.当您为非可选变量声明但不提供值时,它不会nil像可选变量那样设置.没有办法在运行时测试未初始化的非可选变量的使用,因为这种使用的任何可能性都是一个可怕的,编译器检查的程序员错误.将编译的唯一代码是保证每个变量在使用之前被初始化的代码.如果您希望能够nil在运行时分配给变量并检查其值,则必须使用可选项.
示例1:正确使用
func pickThing(choice: Bool) {
let variable: String //Yes, we can fail to provide a value here...
if choice {
variable = "Thing 1"
} else {
variable = "Thing 2"
}
print(variable) //...but this is okay because the variable is definitely set by now.
}
Run Code Online (Sandbox Code Playgroud)
示例2:编译错误
func pickThing2(choice: Bool) {
let variable: String //Yes, we can fail to provide a value here, but...
if choice {
variable = "Thing 1"
} else {
//Uh oh, if choice is false, variable will be uninitialized...
}
print(variable) //...that's why there's a compilation error. Variables ALWAYS must have a value. You may assume that they always do! The compiler will catch problems like these.
}
Run Code Online (Sandbox Code Playgroud)
例3:允许为零
func pickThing3(choice: Bool) {
let variable: String? //Optional this time!
if choice {
variable = "Thing 1"
} else {
variable = nil //Yup, this is allowed.
}
print(variable) //This works fine, although if choice is false, it'll print nil.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6821 次 |
| 最近记录: |