How can I constantly check if the bool value is true / false? SWIFT

Hi, my problem is simple. I have to constantly check if the bool value is true or false, which I still tried to use:

override func update(_ currentTime: TimeInterval) 

in fast mode, and this is a quick way, and as soon as it checks the values, it will constantly repeat the action, although I only want it to execute the action only once, so basically I say that everything I want to check is whether the bool value is true or false once, and then stop checking until it changes. Please help, thanks.

+5
source share
2 answers

Property Observers

You can use Observers properties in Swift to accomplish what you need ... Here's what the docs say about them:

Property observers observe and respond to changes in value properties. Property observers are called every time the value of the set property, even if the new value matches the current properties of the value.

There are observers for the willSet and didSet :

  • willSet is called just before the value is saved.

  • didSet is called immediately after saving the new value.

To solve your problem, you can 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 one or both property observers in your property.

Getters and setters

Alternatively, you can use getters and setters for the saved property to solve your problem:

 private var priv_property:Int = 0 var myProperty:Int{ get { return priv_property } set { priv_property = newValue } } 

Computable properties do not actually retain the value. Instead, they provide a getter and an additional installer to retrieve and set other properties and values ​​indirectly.

+5
source

You must use observers or callbacks. Read the comments below and see @Whirlwind's answer. The solution below is not recommended, as it will be inefficient and may complicate your code. But if you need or need to do this in update() , here is how I would do it:

 // Assume stored property // It might be an API call and so on var boolToWatch = false var lastValueOfWatchedBool: Bool? var lastCheck: TimeInterval = 0 let checkInterval = 1.0 // check every second override func update(_ currentTime: TimeInterval) { // In case boolToWatch is an expensive API call might be good to // check less frequently if currentTime - lastCheck > checkInterval { lastCheck = currentTime // Check for the initial case if lastValueOfWatchedBool == nil { lastValueOfWatchedBool = boolToWatch } // Detect change if boolToWatch != lastValueOfWatchedBool { lastValueOfWatchedBool = boolToWatch // Do what you need to do when the value changed here print("I feel different!") } } } 
-1
source

Source: https://habr.com/ru/post/1265634/


All Articles