Hugo Fouquet Hugo Fouquet - 4 months ago 13
iOS Question

Swift Error in inheritance init class

I have an error when un want init my B object.

My error is :

Use of 'self' in property access 'name' before super.init initializes self


class A {
let name = "myName";
}

class B:A {
let point: ObjectWithName;

init() {
self.point = ObjectWithName(name); // error here
super.init();
}
}


Thanks for your help !

Answer

The problem is that you are accessing name which is declared in the superclass. But the superclass has not been initialized yet (it will after super.init()).

So it's a logic problem.

Solution #1

You to declare point as lazy, this way it will be executed after the whole init process has been completed.

struct ObjectWithName {
    let name: String
}

class A {
    let name = "myName";
}

class B: A {
    lazy var point: ObjectWithName = { ObjectWithName(name:self.name) }()
}

Solution #2

Inside A you can define name as static

class A {
    static let name = "myName";
}

class B:A {
    let point: ObjectWithName;

    override init() {
        self.point = ObjectWithName(name: B.name)
        super.init();
    }
}