Reputation: 149
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 !
Upvotes: 2
Views: 216
Reputation: 59536
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.
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) }()
}
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();
}
}
Upvotes: 1