Does didSet work with tuples in arrays?

I want to know if "didSet" works with tuples in arrays.

I am writing something like the following code, and I want to observe the value of a tuple inside an array. Is it available for this?

var array :[(foo: Int, bar: Int)] = []]{ didSet{ // println code } } init(){ var tuple = (foo: 0, bar:0) array = Array(count: 16, repeatedValue: tuple) } // change the value somewhere in the code // and for example, want to println just only (and when) the value changed array[3].foo = 100 
+8
swift
source share
1 answer

Yes it works:

 var array : [(foo: Int, bar: Int)] = [] { didSet { println("~~~~~~") } } let tup = (foo: 0, bar: 42) array.append(tup) println(array) array[0].foo = 33 println(array) 

didSet is executed every time the array changes, as expected:

~~~~~~
[(0, 42)]
~~~~~~
[(33, 42)]


If you want to know the changed values, use "didSet" + "oldValue" and / or "willSet" + "newValue":

 var array : [(foo: Int, bar: Int)] = [] { willSet { println(newValue) } didSet { println(oldValue) } } let tup = (foo: 0, bar: 42) array.append(tup) array[0].foo = 33 

[(0, 42)]
[]
[(33, 42)]
[(0, 42)]

newValue and oldValue are both variables generated by Swift. Both "willSet" and "didSet" are called when the array changes.

UPDATE:

You can access the actual object with newValue and oldValue . Example:

 var array : [(foo: Int, bar: Int)] = [] { willSet { println(newValue[0].foo) } didSet { if oldValue.count > 0 { println(oldValue[0].foo) } else { println(oldValue) } } } let tup = (foo: 0, bar: 42) array.append(tup) array[0].foo = 33 
+8
source share

All Articles