My understanding so far : If you define an optional variable without assign any values, the compiler will automatically assign the nil
Code Snippets:
A :
var someOptional : Int? //Change to `let` to trigger error
var aDefaultValue = 42
var theAnswer = someOptional ?? aDefaultValue
The code snippet above works fine, however, when I changed the variable someOptional
to a constant, the compiler yelled an error (Please see the attached figure below)
B :
I then tried the similar codes to down to the problem.
var someOptional : Int?
print(someOptional)
Still, it works fine with variable while failed with the constant type.
Conclusion:
If you define a constant optional you have to assign the nil explicitly if you mean that. Because it looks useless (why do you need a constant option with assigned with nil
), if the compiler did that for you automatically it may introduce an error.
Question:
Why does the compiler assume nil
for var
declared optionals but not for let
declared optionals?