在 Swift 中创建属性观察器



我一直在使用Property Observers在变量值更改时操作UI和对象。考虑到这一点,我想知道是否可以为我自己的对象创建自己的属性观察器,例如didSetwillSet。我正在寻找的是能够写这样的东西:

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

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

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

属性观察器绰绰有余。你可以使用这样的东西:

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

最新更新