It's my understanding that
var perhapsInt : Int?
This is automatically set to a .None
value. And the below code snippet confirms that (no compiler errors)
class MyClass {
var num1: Int = 0
var num2: Int?
init(num1: Int) {
self.num1 = num1
}
}
var newClass = MyClass(num1: 5)
newClass.num1 // prints '5'
newClass.num2 // prints 'nil'
Is my understanding of the optional initialisation process correct? if so why does this not work when I change num2
to let
.
I was expecting the same behaviour of optionals defaulting to nil
when using let
. Am I missing something here?
class MyClass {
var num1: Int = 0
let num2: Int?
init(num1: Int) {
self.num1 = num1
// compiler error : return from initialiser without initialising all stored properties
}
}
...
My question is, how can both of these cases be true. Shouldn't it be one or the other. Either optional values are automatically set to .None
or it's not.