在我的最后一个问题中,我询问了如何在Swift中为计算属性的下标编写setter。我认为我的问题还不足以理解。对于一个小任务,给出的答案要么不正确,要么很复杂。经过深思熟虑,我仍然认为也许一个聪明的人可以提供一个更加鼓舞人心的答案。
为了消除混乱,我的问题是Swift中是否存在数组下标的简写setter声明。因为数组有速记setter声明,但没有下标。
一个速记的getter / setter声明是
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
基本上,在针对set动作action[i]
将导致actionButton[i]
更新的情况下。基本上有两种方法可以快速执行此操作。
func setActionAtIndex(index:Int, forValue newValue:SomeClass){
action[index] = newValue
self.updateActionButtonAtIndex(index)
}
上面的解决方案很容易理解,但是,它需要一个函数,该函数在一类中需要两行代码。不太“迅速”。
var action: [SomeClass] {
subscript(index:Int){
set(index:Int,newValue:SomeClass){
action[index] = newValue
//extra action to be performed
updateActionButtonAtIndex(index)
}
get{
return action[index]
}
}
}
不用说,这是绝对错误的,并且这种解决方案是不存在的。
为什么错了?
Expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition
我确实想过另一种方式,但是我不太喜欢。使用扩展名将另一个下标添加到setter数组中-允许您提供回调的setter。这种方法的问题在于您记得提供了回调!这给建立索引的人带来了责任,这可能与您的想法无关。尽管如此,它仍然具有简洁的优点-花费O(0)
时间:
extension Array {
subscript(ix:Int, f:(T,T,Int)->Void) -> T {
set {
let old = self[ix]
self[ix] = newValue
f(old,newValue,ix)
}
get {
return self[ix]
}
}
}
class Thing {
var arr : [Int] = [1, 2, 3]
func f (oldv:Int, newv:Int, ix:Int) {
println("changed \(oldv) to \(newv) at \(ix)")
}
}
var t = Thing()
t.arr[1,t.f] = 100 // "changed 2 to 100 at 1"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句