[英]Stored properties in Swift can't refer to each other?
What is the reason I can't give a value to a stored property
that depends on the value of another one in Swift 2.0? 为什么我不能给依赖于Swift 2.0中另一个
stored property
值的stored property
值的原因是什么?
The code below gives an error saying: 下面的代码给出了一个错误信息:
Something.Type does not have a member named 'foo'
Something.Type没有名为'foo'的成员
class Something {
let foo = "bar"
let baz = "\(foo) baz"
}
This is odd, as Something.Type
certainly does have a member called foo. 这很奇怪,因为
Something.Type
确实有一个名为foo的成员。
Is there a way around this? 有没有解决的办法?
Looks like you're trying to initialise the variable baz
, before swift has had a chance to know that foo
is a property of Something
. 看来您正在尝试初始化变量
baz
,而swift才有机会知道foo
是Something
的属性。 Place your initialisation inside the init
constructor. 将您的初始化放入
init
构造函数中。
class Something {
let foo: String
let baz: String
init () {
foo = "bar"
baz = "\(foo) baz"
}
}
You can also use lazy
initialization but now you have to make it a variable: 您还可以使用
lazy
初始化,但现在必须将其设置为变量:
class Something {
let foo = "bar"
lazy var baz = { "\(self.foo) baz" }()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.