-1

Property Observers当变量值发生变化时,我一直在使用它来操作 UI 和对象。didSet考虑到这一点,我想知道是否可以willSet为我自己的对象创建我自己的 Property Observers。我正在寻找的是能够写出这样的东西:

var someArray: [String] {
    newElementAdded { *some code here* }
}

如您所知didSet并且willSet不跟踪例如将元素添加到数组但跟踪整个数组值的变化。我期待着使用属性观察器来扩展它。我查看了有关闭包和属性的文档,但找不到任何提示。

我的问题是,我如何创建属性观察者?我以上面的一个用例为例,但我的目标是创建自己的观察者。

4

1 回答 1

0

财产观察员绰绰有余。你可以使用这样的东西:

var someArray: [String] = [] {
    didSet {
        stride(from: someArray.count, to: oldValue.count, by: 1).map {
            print("This index doesn't exist anymore:", $0)
        }

        stride(from: 0, to: min(oldValue.count, someArray.count), by: 1)
            .filter { oldValue[$0] != someArray[$0] }
            .forEach { print("The element at index", $0, "has a new value \"\(someArray[$0])\"") }

        stride(from: oldValue.count, to: someArray.count, by: 1).map {
            print("New value \"\(someArray[$0])\" in this index", $0)
        }
    }
}

someArray.append("Hello")
//New value "Hello" in this index 0

someArray.append("world")
//New value "world" in this index 1

someArray = ["Hello", "world"]
//Nothing is printed since no elements have changed

someArray.append("!")
//New value "!" in this index 2

someArray.remove(at: 1)
//This index doesn't exist anymore: 2
//The element at index 1 has a new value "!"

someArray.append(contentsOf: ["✋", ""])
//New value "✋" in this index 2
//New value "" in this index 3
于 2018-10-19T22:17:44.573 回答