Get notified when element added/removed to array

前端 未结 1 2011
生来不讨喜
生来不讨喜 2021-02-08 06:19

I wanted to be notified when an element added/removed from an array. If we are not talking about arrays, for example to be notified when a string is changed, there is a good sol

相关标签:
1条回答
  • 2021-02-08 07:10

    You can create proxy like class/struct that will have same interface as array, will store standard array under the scenes and will act on behalf of store array. Here is small example:

    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)
    
    0 讨论(0)
提交回复
热议问题