Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 212
Balaach Avatar asked Mar 18 '17 06:03

Balaach


1 Answers

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.

like image 185
Whirlwind Avatar answered Oct 12 '22 01:10

Whirlwind