ios - 当元素添加/删除到数组时得到通知

标签 ios arrays swift

我想在数组中添加/删除元素时收到通知。如果我们不是在谈论数组,例如在字符串更改时收到通知,swift 中有一个很好的解决方案:

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

当我向数组添加/删除元素时,我们能否获得类似的结果?

最佳答案

您可以创建类似类/结构的代理,它们将具有与数组相同的接口(interface),将在场景下存储标准数组并代表存储数组。这是一个小例子:

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)

关于ios - 当元素添加/删除到数组时得到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27041493/

相关文章:

swift - 如何在 placeholderView 的 ViewController 中加载 nib

ios - View 出现模态视图动画而不是显示(推送)动画

ios - 功能差异,UINavigationController与仅Storyboard Segue

ios - CocoaPods 不工作

android - Cordova 在 WebView 中单击通过 WhatsApp 共享

ios - 如何将 Crashlytics 集成到 iOS 框架目标中?

JAVA:从文件中读取下一行,排除所有空格

php - 使用 ng-repeat 循环遍历格式类似于字符串的数组

c# - 字节流中的双值传输

ios - 核心情节使我的应用使用乐器崩溃