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?
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:允许零
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-TIME中未初始化的类变量。所以你必须在使用前检查它以防止应用程序崩溃。怎么样?只有将变量更改为可选项? – Dmitry
是的,如果你试图让一个变量在运行时没有任何值,那么你必须声明该变量是可选的。你不能声明一个非可选变量,而不必为它提供一个初始值。将变量未初始化在声明的确切行上的功能只能让您在稍后几行提供初始值。编译器将不允许您在代码中包含变量,除非它肯定提供了值。 – andyvn22
但是Swift不是类型安全的语言。在语言概念上似乎有一个很大的问题。不仅编译器不检查代码是否安全 - 甚至开发人员(!)都无法做到这一点!只有在任何情况下他使用可选项代替变量。 – Dmitry
这可能是编译器的异常,你不会得到一个错误声明一个变量这样
class MyClass {}
var myClass : MyClass
,但在游乐场你会得到一个运行时错误时,你刚才读的变量
myClass
variable 'myClass' used before being initialized
Swift最重要的功能之一是非可选变量永远不会是零。如果你尝试访问这个变量,你会得到一个运行时错误,也就是崩溃。
请提供您的完整代码,包括周围的类定义:您发布的代码不会编译。 – andyvn22
@ andyvn22你的意思是你在第三行发生错误?我已经修复了代码,但还没有检查它。 – Dmitry
不是我倒下了,但最后一行拒绝编译。错误:'二进制运算符'=='不能应用于类型'myClass'和'NilLiteralConvertible''的操作数 –