The Constant property cannot be initialized in the convenience initializer of a derived class

Below is an example of code from the playground. I do not understand why the variable bin the subclass must be of type var and cannot be let. Can someone help me understand?

class Base1 {
    init() { }
}

class Sub1: Base1 {
    let b: Int

    override init() {
        super.init()
    }

    convenience init(b: Int) {
        self.b = b  // Cannot assign to property: 'b' is a 'let' constant
        self.init()
    }
}
+4
source share
3 answers

I think this is less related to the subclass and more related to the class initializers.

The error shows only half the history, a change bfrom letto varwill show other problems with this class:

  • . init, b.

  • self

( Martin R , , b let):

class Base1 {
    init() { }
}

class Sub1: Base1 {
    let b: Int

    convenience override init() {
        self.init(b: 5)
    }

    init(b: Int) {
        self.b = b
        super.init()
    }
}

let one = Sub1(b: 10)
one.b   // prints 10
let two = Sub1()
two.b   // prints 5
+2

, imho, , .

-, , "" . "" ( ) , , (, ). self.b init , b init:

class Sub1: Base1 {
    let b: Int

    // You must init b
    // Or ger error: property 'self.b' not initialized ...
   init(b: Int) {
        self.b = b
        super.init()
    }

    // Do you really need the code below now?
    //convenience init(b: Int) {
    //    self.b = b
    //    self.init()
    //}
}

, init b, , , .

-, , . , . , - :

...

convenience init(b: Int) {
    self.b = b
    self.init(c: 10)
}

// later some crazy guy adds his own "convenience" initializer and points your to this one.
convenience init(c: Int) {
    self.c = c
    if c == 7 {
       self.b = 11
    }
    self.init()
}

, "" , b ​​ ?

, :

class Base1 {
    init() {}
}


class Sub1: Base1 {
    let b: Int

    init(b: Int) {
        self.b = b
        super.init()
    }

    // Convenience initializer providing default value
    override convenience init() {
        self.init(b: 7)
    }
}

, , , , let b init?

+1

Swift . documentation:

. , .

, .

. , clearer .

, , , init . b var, .

class Sub1: Base1 {
    var b: Int?

    override init() {
        super.init()
    }

    convenience init(b: Int) {
        self.init()
        self.b = b
    }
}

, @Martin R init, :

class Sub1: Base1 {
    let b: Int

    init(b: Int) {
        self.b = b
        super.init()
    }

    convenience override init() {
        self.init(b:5)
    }
}
+1

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


All Articles