Swift属性-Getter Ivar [英] Swift property - getter ivar
问题描述
在Swift getter中是否应该使用ivar属性?我的代码导致吸气剂调用吸气剂,直到程序崩溃:
Is there an ivar property we should use in a Swift getter? My code is causing the getter to call the getter until the program crashes:
var document: UIDocument? {
get {
return self.document
}
set {
self.document = newValue
useDocument()
}
}
推荐答案
Swift属性没有像在Objective-C中那样具有独立的基础存储的概念.相反,您需要创建第二个(私有)属性并将其用作存储:
Swift properties do not have the concept of separate, underlying storage like they do in Objective-C. Instead, you'll need to create a second (private) property and use that as the storage:
private var _document: UIDocument?
var document: UIDocument? {
get {
return _document
}
set {
_document = newValue
useDocument()
}
}
如果您只想在设置document
属性后调用useDocument()
,则可以省略getter,setter和private属性,而只需使用willSet
或didSet
.
If all you're trying to do is call useDocument()
after the document
property is set, you can omit the getter, setter, and private property and instead just use willSet
or didSet
.
这篇关于Swift属性-Getter Ivar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!