2

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 !

1 Answer 1

1

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 can declare point as lazy, this way it will be executed after the whole init process has been completed, unless you call it before.

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.