簡體   English   中英

“didSet”是否與數組中的元組一起使用?

[英]Does “didSet” work with tuples in arrays?

我想知道“didSet”是否與數組中的元組一起使用。

我正在編寫類似下面的代碼,我想觀察數組中的元組值。 可以做那種事情嗎?

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

是的有效:

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 ,如預期的那樣:

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


如果您想知道更改的值,請使用“didSet”+“oldValue”和/或“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)]

newValueoldValue都是Swift生成的變量。 修改數組時,都會調用“willSet”和“didSet”。

更新:

您可以訪問newValueoldValue背后的實際對象。 例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM