我不想要init我的B对象时出错。
我的错误是: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();
}
}
感谢您的帮助!
答案 0 :(得分:1)
问题是您正在访问在超类中声明的name
。但是超类尚未初始化(它将在super.init()
之后)。
所以这是一个逻辑问题。
您可以将point
声明为lazy
,这样就可以在整个init
进程完成后执行,除非您之前调用它。
struct ObjectWithName {
let name: String
}
class A {
let name = "myName";
}
class B: A {
lazy var point: ObjectWithName = { ObjectWithName(name:self.name) }()
}
在A
内,您可以将name
定义为static
class A {
static let name = "myName";
}
class B:A {
let point: ObjectWithName;
override init() {
self.point = ObjectWithName(name: B.name)
super.init();
}
}