Fast optional initialization

I understand that

var perhapsInt : Int?

This value is automatically set to .None. And the code snippet below 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'

Do I understand the process of optional initialization correctly? if so, why doesn’t it work when I change num2to let.

I expected the same default options behavior nilwhen used let. Did I miss something?

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 both of these cases can be true. Shouldn't it be anyway. For any additional values, a value is automatically set .Noneor not.

+4
2

var num2: Int? , Optional . Swift, (.None).

, var num2: Int ( ?) - , var vs. let.

class MyClass {
    var num2: Int
    init() {
        // Return from initializer without initializing all stored properties
    }
}

let s ' ( var s'), , :

class MyClass {
    let num2: Int? = nil
}

// or this way

class MyClass {
    let num2: Int?
    init() {
        num2 = nil
    }
}

, , nil.


.

+5

, . -

, .

, , let, :

let num2: Int? = .None
let num2: Int? = nil
0

Source: https://habr.com/ru/post/1615951/


All Articles