我如何知道数组中元素的值是否已更改?

时间:2016-12-13 10:09:22

标签: arrays swift valuechangelistener

使用的语言: Swift 2.3

例如,我有一个名为Doctor

的模型
class Doctor {
    var name = ""
    var number = 123
    init(name:String, number:String) { 
        self.name = name
        self.number = number
    }
}

在另一个班级我把它变成了一个数组

class SomeClass {
    var doctors:[Doctor] = [
        Doctor(name: "Matt Smith", number: 11),
        Doctor(name: "David Tennant", number: 10),
        Doctor(name: "Peter Capaldi", number: 12)
    ]
}

然后由于某种原因我决定更改index#2

的值
class SomeClass {
    ...
    // let's just say that this code was executed inside the code somewhere....
    func change() {
        doctors[2].name = "Good Dalek"
        // or
        doctors[2] = Doctor(name: "Christopher Eccleston", number: 9)
    }
    ...
}

我怎么知道doctors数组的值与以前不一样?

我知道filtersort函数。我也知道如何使用didSet以便我可以这样做

var doctors:[Doctor] = [] {
    didSet {
        // do something if `doctors` was changed
    }
}

1 个答案:

答案 0 :(得分:1)

只需将doctors数组设为property observer

即可
class Doctor {
    var name = ""
    var number = 123
    init(name:String, number:Int) {
        self.name = name
        self.number = number
    }
}


class SomeClass {
    var doctors: [Doctor] = [
        Doctor(name: "Matt Smith", number: 11),
        Doctor(name: "David Tennant", number: 10),
        Doctor(name: "Peter Capaldi", number: 12)
        ] {
        didSet {
            print("doctros array has been modifed!")
        }
    }
}


let someClass = SomeClass()
someClass.doctors[0] = Doctor(name: "New Doctor", number: 13) // "doctros array has been modifed!"

someClass.doctors.append(Doctor(name: "Appended Doctor", number: 13)) // "doctros array has been modifed!"

someClass.doctors.remove(at: 0) // "doctros array has been modifed!"

请注意,添加,编辑或删除操作都会影响doctors数组调用didSet代码(print("doctros array has been modifed!"))。