我希望在从数组中添加/删除元素时收到通知。如果我们不讨论数组,例如在更改字符串时收到通知,那么swift中有一个很好的解决方案:
private var privateWord: String?
var word: String? {
get {
return privateWord
}
set {
if newValue != "" {
notifyThatWordIsChanged()
} else {
notifyThatWordIsEmpty()
}
privateWord = newValue
}
}
当我向数组添加/删除元素时,我们能否得到类似的结果吗?
答案 0 :(得分:4)
您可以创建类似于类/结构的代理,它将具有与数组相同的接口,将在场景下存储标准数组,并将代表商店数组。这是一个小例子:
struct ArrayProxy<T> {
var array: [T] = []
mutating func append(newElement: T) {
self.array.append(newElement)
print("Element added")
}
mutating func removeAtIndex(index: Int) {
print("Removed object \(self.array[index]) at index \(index)")
self.array.removeAtIndex(index)
}
subscript(index: Int) -> T {
set {
print("Set object from \(self.array[index]) to \(newValue) at index \(index)")
self.array[index] = newValue
}
get {
return self.array[index]
}
}
}
var a = ArrayProxy<Int>()
a.append(1)