我希望在从数组中添加/删除元素时收到通知.如果我们不是在讨论数组,例如在更改字符串时收到通知,那么在
swift中有一个很好的解决方案:
private var privateWord: String? var word: String? { get { return privateWord } set { if newValue != "" { notifyThatWordIsChanged() } else { notifyThatWordIsEmpty() } privateWord = newValue } }
解决方法
您可以创建类似于class / struct的代理,它将具有与array相同的接口,将在场景下存储标准数组并代表store数组.这是一个小例子:
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)