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 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()
}
}
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
.
If what you are trying to achieve is add some custom processing when the property is set, you don't need to define a separate backing data member and implement a computed property: you can use the willSet
and didSet
property observers, which are automatically invoked respectively before and after the property has been set.
In your specific case, this is how you should implement your property:
var document: UIDocument? {
didSet {
useDocument()
}
}
Suggested reading: Property Observers
In your code there is an infinite recursion situation: for example, self.document
inside the getter keep calling the getter itself.
You need to explicitly define an ivar yourself. Here is a possible solution:
private var _document:UIDocument?
var document: UIDocument? {
get {
return self._document
}
set {
self._document = newValue
useDocument()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With