Hello my problem is simple I have to constantly check whether the value of a bool is true or false, what I have tried so far is to use the:
override func update(_ currentTime: TimeInterval)
function in swift and it is way to fast and once it checks the values it will constantly repeat the action even though I only wish for it to perform the action only once, so basically what I'm saying is that all I want to do is to check whether the bool value is true or false once and then stop checking until it changes again. Please help, thank you.
Property Observers
You can use Property Observers in Swift to accomplish what you need... Here is what docs says about these:
Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.
There are willSet
and didSet
property observers:
willSet is called just before the value is stored.
didSet is called immediately after the new value is stored.
To solve your problem, you could do something like this:
var myProperty:Int = 0 {
willSet {
print("About to set myProperty, newValue = \(newValue)")
}
didSet{
print("myProperty is now \(myProperty). Previous value was \(oldValue)")
}
}
You can implement either one or both of property observers on your property.
Getters and Setters
As an alternative, You can use getters and setters on a stored property to solve your problem:
private var priv_property:Int = 0
var myProperty:Int{
get {
return priv_property
}
set {
priv_property = newValue
}
}
Computed properties do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
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