得到通知时添加的元素/删除数组 [英] Get notified when element added/removed to array

查看:86
本文介绍了得到通知时添加的元素/删除数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,当一个元素添加/从阵列中删除时得到通知。如果我们不是在谈论阵列,因为当一个字符串改变被通知例如,有斯威夫特一个好的解决方案:

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 solution in swift:

private var privateWord: String?
var word: String? {
    get {
        return privateWord
    }
    set {
        if newValue != "" {
            notifyThatWordIsChanged()
        } else {
            notifyThatWordIsEmpty()
        }
        privateWord = newValue
    }
}

我们可以achive类似的结果,当我添加/删除元素的数组?

Can we achive a similar result, when I add/remove an element to an array?

推荐答案

您可以创建一个像类/结构,将有相同的接口阵列,将存储场景下的标准阵列,并代为存储阵列的代理。这里是小例子:

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)

这篇关于得到通知时添加的元素/删除数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆