Reputation: 22946
I need the code in didSet
to be executed without changing the property's value.
Coming from Objective-C recently, there doesn't seem to be a setMyProperty()
.
So I tried:
self.myProperty = self.myProperty
which result in error Assigning a property to itself
.
Because myProperty
happens to be CGFloat
, I could do:
self.myProperty += 0.0
which does trigger didSet
and does not affect the value, but it doesn't show what I mean to do here.
Is there a way to call didSet
in a more clear/direct way?
Upvotes: 11
Views: 4954
Reputation: 2660
You can use a tuple Swift 3
var myProperty : (CGFloat,Bool) = (0.0, false){
didSet {
if myProperty.1 {
myProperty = (0.0, false) // or (oldValue.0, false)
//code.....
}else{
// code.....
}
}
}
myProperty = (1.0, true)
print(myProperty.0) //print 0.0
myProperty = (1.0, false)
print(myProperty.0) //print 1.0
myProperty = (11.0, true)
print(myProperty.0) //print 0.0
Upvotes: 0
Reputation: 1403
didSet is called after the property value has already been changed. If you want to revert it to it's previous value(so having the same effect as not changing the property's value), you need to assign it 'oldValue' property. Please take note that oldValue is not a variable defined by you, it comes predefined.
var myProperty: CGFloat {
didSet {
myProperty = oldValue
}
}
Upvotes: 0
Reputation: 22939
You could do:
struct MyStruct {
var myProperty: CGFloat {
didSet {
myFunc()
}
}
func myFunc() { ... }
}
Here myFunc
will be called when myProperty
is set. You can also call myFunc
directly, such as in the situation you required didSet
to be called.
Upvotes: 2