I want to know if "didSet" works with tuples in arrays.
I'm writing something like the following code and I want to observe the tuple's value inside the array. Is it available to do that sort of thing?
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
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 each time the array is modified, 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 is modified.
UPDATE:
You can access the actual object behind 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With