如何检查变量是否未在Swift中初始化?

时间:2015-09-26 14:30:06

标签: swift null optional

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?

2 个答案:

答案 0 :(得分:12)

您是对的 - 您可能无法将非可选变量与nil进行比较。当您为非可选变量声明但不提供值时, not 设置为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.
}

示例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.
}

示例3:允许nil

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.
}

答案 1 :(得分:0)

编译器的异常可能是你没有收到以这种方式声明变量的错误

class MyClass {}
var myClass : MyClass

但是在Playground中,只读取变量

时会出现运行时错误
myClass
  

变量'myClass'在初始化之前使用

Swift最重要的特性之一是非可选变量永远不会是零。如果您尝试访问该变量,您将收到运行时错误,即崩溃。