Execute a method when a variable value changes in Swift Execute a method when a variable value changes in Swift ios ios

Execute a method when a variable value changes in Swift


You can simply use a property observer for the variable, labelChange, and call the function that you want to call inside didSet (or willSet if you want to call it before it has been set):

class SharingManager {    var labelChange: String = Model().callElements() {        didSet {            updateLabel()        }    }    static let sharedInstance = SharingManager()}

This is explained in Property Observers.

I'm not sure why this didn't work when you tried it, but if you are having trouble because the function you are trying to call (updateLabel) is in a different class, you could add a variable in the SharingManager class to store the function to call when didSet has been called, which you would set to updateLabel in this case.


Edited:

So if you want to edit a label from the ViewController, you would want to have that updateLabel() function in the ViewController class to update the label, but store that function in the singleton class so it can know which function to call:

class SharingManager {    static let sharedInstance = SharingManager()    var updateLabel: (() -> Void)?    var labelChange: String = Model().callElements() {        didSet {            updateLabel?()        }    }}

and then set it in whichever class that you have the function that you want to be called, like (assuming updateLabel is the function that you want to call):

SharingManager.sharedInstance.updateLabel = updateLabel

Of course, you will want to make sure that the view controller that is responsible for that function still exists, so the singleton class can call the function.

If you need to call different functions depending on which view controller is visible, you might want to consider Key-Value Observing to get notifications whenever the value for certain variables change.

Also, you never want to initialize a view controller like that and then immediately set the IBOutlets of the view controller, since IBOutlets don't get initialized until the its view actually get loaded. You need to use an existing view controller object in some way.

Hope this helps.


In Swift 4 you can use Key-Value Observation.

label.observe(\.text, changeHandler: { (label, change) in    // text has changed})

This is basically it, but there is a little catch. "observe" returns an NSKeyValueObservation object that you need to hold! - when it is deallocated, you’ll receive no more notifications. To avoid that we can assign it to a property which will be retained.

var observer:NSKeyValueObservation?// then assign the return value of "observe" to itobserver = label.observe(\.text, changeHandler: { (label, change) in    // text has changed,})

You can also observe if the the value has changed or has been set for the first time

observer = label.observe(\.text, changeHandler: { (label, change) in    // just check for the old value in "change" is not Nil    if let oldValue = change.oldValue {        print("\(label.text) has changed from \(oldValue) to \(label.text)")    } else {        print("\(label.text) is now set")    }})

For More Information please consult Apples documentation here


Apple provide these property declaration type :-

1. Computed Properties:-

In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

var otherBool:Bool = falsepublic var enable:Bool {    get{        print("i can do editional work when setter set value  ")        return self.enable    }    set(newValue){        print("i can do editional work when setter set value  ")        self.otherBool = newValue    }}

2. Read-Only Computed Properties:-

A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.

var volume: Double {    return volume}

3. Property Observers:-

You have the option to define either or both of these observers on a property:

willSet is called just before the value is stored.
didSet is called immediately after the new value is stored.

public  var totalSteps: Int = 0 {    willSet(newTotalSteps) {        print("About to set totalSteps to \(newTotalSteps)")    }    didSet {        if totalSteps > oldValue  {            print("Added \(totalSteps - oldValue) steps")        }    }}

NOTE:- For More Information go on professional linkhttps://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html