Oscar Apeland
Oscar Apeland

Reputation: 6662

Monitor changes to an array object

I have no idea if this is possible at all, but it would save me from a lot of stress and bad code. Is it possible to monitor whenever an array gets updated? For example, method A changes the array a=[1,2,3] to a=[1,2,3,4], is it possible to have a sort of delegate that gets triggered when a is updated?

Upvotes: 20

Views: 10691

Answers (1)

Jeremy Pope
Jeremy Pope

Reputation: 3352

If your array is a property in your class, you can use property observers. willSet is called before the change, didSet is called after. It is really easy.

var myArray:[Int] = [1, 3, 4] {
    didSet {
        println("arrayChanged")
    }
}

This will print array changed if I add an Int, remove and Int, etc. I generally put it on one line though:

var myArray:[Int] = [1, 3, 4] { didSet { println("arrayChanged") } }

Upvotes: 39

Related Questions