英文:
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()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论