The compiler currently warns us if we try to use a constant before it is initialized on all paths through the program:
let x: Int
print(x) // Error: "Constant 'x' used before being initialized"
The same thing happens for non-optional variables:
var x: Int
print(x) // Error: "Variable 'x' used before being initialized"
Optional variables and implicitly unwrapped Optionals, however, seem to be silently initialized with .none
and can be used before assigning another value to it. The following snippet compiles just fine:
var x: Int?
print(x) // prints "nil"
I think that the default initialization of Optionals is potentially dangerous, as it makes it possible to forget to initialize an Optional with a proper value on some paths:
var x: Int?
if f() {
x = 5
} else {
// forgot to initialize x
}
print(x)
Similarly, it makes it possible to forget to initialize stored properties in a struct or class:
struct X {
init() {
// forgot to initialize self.x
}
var x: Int?
}
The latter becomes especially painful when adding new stored properties to a type that has a lot of initializers — it is super easy to forget initializing the property in one of them.
Personally I don't think there's a reason to implicitly initialize Optionals with .none
and treat them any differently than non-optional variables or constants, especially since we can't turn that behavior off. And if that's what we desire, it would be as simple as adding a = nil
to the declaration.
What do you guys think about removing the default initialization with .none
of Optionals?