Yes it's correct
An optional variable doesn't need to be manually initialized. If you read it before having populated it does contain nil
.
From Apple docs
If you define an optional variable without providing a default value, the variable is automatically set to nil for you [...]
On the other hand the compiler does force you to manually initialize an Optional constant (let
) before you can read it.
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 [...]
Why?
A constant can be written only once. It doesn't need to happened on the same line it is initialized but it must happened before your read it.
E.g. this code works fine
let num: Int?
num = 1
print(num)
However if the compiler had put a temporary nil
value inside num
then the constant would have been wrote twice. Which is against the concept of constant.
let num: Int?
print(num) // nil ??? <- this can't work!
num = 1
print(num) // 1
Another example
This code snippet works fine
func printArea(width: Int?, height:Int?) {
let area: Int?
if let width = width, height = height {
area = width * height
} else {
area = nil
}
print(area)
}
Again, if the compiler had put a temporary nil
value inside area
then...
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)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…