Mike Strong Mike Strong - 5 months ago 31
iOS Question

how do I listen for a change of value in a variable using swift?

I have a string type variable thats value is updated via a PickerView, and when that value gets updated, it then updates the title of a button, like so:

@IBOutlet weak var selectedCountry: UIButton!

var pickedCountry: String?

func checkForPickedCountry() {
if self.pickedCountry != nil {
selectedCountry.setTitle("\(pickedCountry!)", forState: .Normal);
} else {
selectedCountry.setTitle("Tap here pick a country", forState: .Normal);
}


however, whenever the value of
var pickedCountry
is changed I would like to shoot a function.. How do I not only check if the value is
nil
or not but if it was changed from the previous value?

Answer

You can implement willSet in your variable to call your function everytime when variable is changing. Also you can modify your function to get new value like this:

var pickedCountry: String? {
    willSet(newValue) {
      checkForPickedCountry(newValue ?? "")
    }
}

func checkForPickedCountry(updatedValue: String) {...}
Comments