到目前为止我的理解:如果你定义一个可选变量而不分配任何值,编译器会自动分配nil
代码片段:
答:
var someOptional : Int? //Change to `let` to trigger error
var aDefaultValue = 42
var theAnswer = someOptional ?? aDefaultValue
上面的代码片段工作正常,但是,当我将变量 someOptional
更改为常量时,编译器报错(请参见下面的附图)
B:
然后我尝试了类似的代码来解决问题。
var someOptional : Int?
print(someOptional)
尽管如此,它对于变量来说工作得很好,而对于常量类型却失败了。
结论:
如果你定义了一个常量可选值,你必须显式地指定 nil(如果你是这么想的话)。因为它看起来没什么用(为什么你需要一个用 nil
分配的常量选项),如果编译器自动为你这样做,它可能会引入错误。
问题:
为什么编译器对于 var
声明的可选值假设为 nil
,但对于 let
声明的可选值则不假设?
最佳答案
是的,正确
可选变量不需要手动初始化。如果您在填充之前阅读它,它确实包含 nil
。
来自苹果docs
If you define an optional variable without providing a default value, the variable is automatically set to nil for you [...]
另一方面,编译器确实会强制您在读取可选常量 (let
) 之前手动初始化它。
Unlike a variable, the value of a constant cannot be changed once it is set. Attempting to do so is reported as an error when your code is compiled [...]
为什么?
常量只能写入一次。它不需要发生在初始化的同一行,但它必须发生在您读取它之前。
例如这段代码工作正常
let num: Int?
num = 1
print(num)
但是,如果编译器在 num
中放入临时 nil
值,则该常量将被写入两次。这违背了常数的概念。
let num: Int?
print(num) // nil ??? <- this can't work!
num = 1
print(num) // 1
另一个例子
这段代码运行良好
func printArea(width: Int?, height:Int?) {
let area: Int?
if let width = width, height = height {
area = width * height
} else {
area = nil
}
print(area)
}
同样,如果编译器在 area
中放置了一个临时 nil
值,那么...
func printArea(width: Int?, height:Int?) {
let area: Int?
print(area) // not possible! area is going to change in a moment
if let width = width, height = height {
area = width * height
} else {
area = nil
}
print(area)
}
关于swift - 默认情况下,常量未分配的可选值不会为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58796939/