Creating Property Observers in Swift

439 Views Asked by At

I've been using Property Observers to manipulate UI and objects when a variable value has changed. With that in mind, I was wondering if it's possible to create my own Property Observers such as didSet and willSet for my own objects. what I'm looking for is to be able to write something like this:

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

As you know didSet and willSet do not track for example adding an element to an array but however tracks changes of the entire array value. I'm looking forward to maybe extend that using the property observers. I looked into the documentation about closures and properties and I couldn't find any hints.

My question is, how could I create property observers ? I gave one of the use cases above as an example, but I'm aiming at creating my own observers.

1

There are 1 best solutions below

0
ielyamani On

The property observers are more than sufficient. You could use something like this:

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