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

How can I check if a variable is not initialized in 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?

你是对的——你不能将非可选变量与 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.
}

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

您以这种方式声明变量时不会出错,这可能是编译器的异常

class MyClass {}
var myClass : MyClass

但在 Playground 中,当您读取变量时会出现运行时错误

myClass

variable 'myClass' used before being initialized

Swift 最重要的特征之一是非可选变量永远不能为 nil。如果您尝试访问该变量,您将遇到运行时错误,也就是崩溃。