Swift懒惰使用self实例化 [英] Swift lazy instantiating using self
问题描述
我有一个让我真正困惑的事情,特别是以下代码触发了编译器错误"unresolved identifier self",我不确定为什么会这样,因为懒惰意味着在使用该属性时,该类已经实例化.我想念什么吗?
I have something that really puzzles me, specifically the following code triggers a compiler error "unresolved identifier self", and I am not sure why this is happening, as lazy means that at the time the property will be used, the class is already instantiated. Am I missing something?
非常感谢.
这是代码
class FirstClass {
unowned var second: SecondClass
init(second:SecondClass) {
self.second = second
print("First reporting for duty")
}
func aMethod() {
print("First's method reporting for duty")
}
}
class SecondClass {
lazy var first = FirstClass(second: self)
func aMethod() {
first.aMethod()
}
}
推荐答案
由于某种原因,惰性属性需要显式类型注释,如果其
初始值为self
.在 swift-evolution邮件列表中已提及,但是我无法解释为什么
For some reason, a lazy property needs an explicit type annotation if its
initial value refers to self
. This is mentioned on the swift-evolution mailing list, however I cannot explain why that is
necessary.
使用
lazy var first: FirstClass = FirstClass(second: self)
// ^^^^^^^^^^^^
您的代码将按预期编译并运行.
your code compiles and runs as expected.
这是另一个示例,它表明出现了问题
也与struct
相同,即,它与子类化无关:
Here is another example which demonstrates that the problem occurs
also with struct
s, i.e. it is unrelated to subclassing:
func foo(x: Int) -> Int { return x + 1 }
struct MyClass {
let x = 1
lazy var y = foo(0) // No compiler error
lazy var z1 = foo(self.x) // error: use of unresolved identifier 'self'
lazy var z2: Int = foo(self.x) // No compiler error
}
y
的初始值不依赖于self
,并且不需要
类型注释. z1/z2
的初始值取决于self
,
并且只能使用显式类型注释进行编译.
The initial value of y
does not depend on self
and does not need a
type annotation. The initial values of z1/z2
depend on self
,
and it compiles only with an explicit type annotation.
更新:此已在Swift中修复 4/Xcode 9 beta 3,
惰性属性初始值设定项现在可以引用实例成员,而无需显式的self
和显式的类型注释. (感谢@hamish进行更新.)
Update: This has been fixed in Swift 4/Xcode 9 beta 3,
lazy property initializers can now reference instance members without explicit self
, and without explicit type annotation. (Thanks to @hamish for the update.)
这篇关于Swift懒惰使用self实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!