Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 640
Oscar Apeland Avatar asked Feb 11 '15 01:02

Oscar Apeland


1 Answers

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") } }
like image 135
Jeremy Pope Avatar answered Oct 06 '22 07:10

Jeremy Pope