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

标签 swift null option-type

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

关于swift - 如何检查变量是否未在 Swift 中初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798259/

相关文章:

exception - 在取消引用之前检查 null 或仅通过异常捕获 null 引用

java - 当我需要使用 Optional.orElseGet() 而不是 Optional.orElse()

swift - 为什么有必要将 Optional 强制转换为 Any?

ios - 最后一行的 UITableView indexPath

ios - 在 Swift 中更改 MKMapView 上的图钉图像

json - 为什么我无法从 Alamofire 获取请求结果

swift - '强制为任何',但属性是 UIColor 类型

swift - Xcode 一次又一次地显示错误“你想在 Swift 中添加协议(protocol) stub 吗?”

c++ - 对取消引用的 NULL 指针的引用是否会在 C++ 中创建或访问时产生 UB

java - PSQL异常 : ERROR: null value in column violates not-null constraint