I have code like this:
@IBInspectable var myProperty: String? {
set(newValue) {
//logic for setter
}
get {
return myProperty
}
}
The above code generates a warning:
Attempting to access 'myProperty' within its own getter. Access 'self' explicitly to silence this warning.
So I fix the code as suggested:
@IBInspectable var myProperty: String? {
set(newValue) {
//logic for setter
}
get {
return self.myProperty
}
}
The problem would be solved but I am using SwiftFormat during the application build phase. And SwiftFormat automatically removes the self keyword, treating it as unnecessary here.
I see two solutions:
What would be the best choice for this?
Your code is incorrect in the first place. Adding self
will not help.
What you have created is infinite recursion. When myProperty
's getter is called, you return myProperty
, which calls the getter again. in the getter you return myProperty
again and this calls the getter again. This will go on forever until the stack overflows.
If you just want a custom setter, you can try willSet
or didSet
.
var myProperty: String {
willSet(newValue) {
// do stuff
}
}
// or
var myProperty: String {
didSet(oldValue) {
// do stuff
}
}
I hit this same warning when attempting to write an Objective-C style property with a backing ivar:
var myProperty: String {
guard let myProperty = _myProperty else {
_myProperty = "some string"
return myProperty // Attempting to access 'myProperty' within its own getter
}
return myProperty
}
var _myProperty: String? = nil
Expanding the error message in Xcode, however, shows that the warning has a hint on the second line:
// Attempting to access 'myProperty' within its own getter
// Access 'self' explicitly to silence this warning
Changing to return self.myProperty
thus silences the warning in cases where the calls will not cause infinite recursion.
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