Swift: 计算属性 – 在值更改时调用函数

huangapple go评论61阅读模式
英文:

Swift: Computed Property - call function when value changed

问题

我需要一个变量来保留对对象数组的选定索引。

每当此索引更改时,我需要进行函数调用。

我曾认为计算属性是解决方法,但我遇到了递归问题。

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

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

我该如何修复这个问题?

英文:

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

得分: 2

只需要为存储属性添加一个 didSet

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

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

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

huangapple
  • 本文由 发表于 2023年6月29日 19:01:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定