vrthmy5312
vrthmy5312

Reputation: 107

Constant check for variable change

Would there be a way to continuously check if a variable has changed in swift?

I have tried a basic timer idea, which is not very smart as it did not work precisely down to the millisecond of allowed disruption and is probably highly unpredictable and glitchy. Would there be a way to design such a checker? Ideally, could it be created within a waiting method such as this:

DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
})

What I mean with this is that while this waiting timer is waiting, could it have a sort of exception breaking it and executing a different code if a specified variable has changed?

Upvotes: 1

Views: 279

Answers (2)

Sweeper
Sweeper

Reputation: 271955

If you can edit the property yourself (i.e. you wrote the property yourself), you can consider using a didSet block:

var someProperty: String {
    didSet {
        print("Got a new value: \(newValue)")
    }
}

If the property is not written by you but is exposed to Objective-C, you can do some Key-value Observing:

@objc class MyClass : NSObject {
    @objc dynamic var someProperty: String = "Hello"
}

let obj = MyClass()
obj.observe(\.someProperty) { (myClass, value) in
    print("Got a new value: \(myClass.someProperty)")
}
obj.someProperty = "Changed!"

Upvotes: 2

Duncan C
Duncan C

Reputation: 131426

What you want is key-value observing. There is Foundation support for KVO of NSObject properties, and there is support for native Swift KVO in Swift 4.

Upvotes: 1

Related Questions