swiftcomputed-properties

Swift: Computed Property - call function when value changed


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?


Solution

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

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