Swift: Computed Property - call function when value changed

245 Views Asked by At

I have need of a variable that retains the selected index into an array of objects.

I need to make a function call whenever this index changes.

I had thought that computed properties were the way to go but I'm having problems with recursion

var selectedIndex : Int = 0
{
  get
  {
    return self.selectedIndex
  }

  set
  {
    self.selectedIndex = newValue
    self.delegate?.updatedValue()
  }
}

How can I fix this?

1

There are 1 best solutions below

0
Dávid Pásztor On BEST ANSWER

You just need to add a didSet to the stored property.

var selectedIndex : Int = 0 {
  didSet {
    self.delegate?.updatedValue()
  }
}