Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading