How do I know if a value of an element inside an array was changed?

为君一笑 提交于 2019-12-12 03:54:21

问题


Language Used: Swift 2.3

For example I have a model called Doctor

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

And in another class I made it into an array

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

And then for some reason I decide to change the value of 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)
    }
    ...
}

How will I know that the value of the doctors Array is not the same as before?

I do know of filter and sort functions. I also know how to use didSet such that I could do this

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

回答1:


Simply, by letting doctors array to be as 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!"

Note that each of adding, editing or deleting operations affects doctors array calls the didSet code (print("doctros array has been modifed!")).



来源:https://stackoverflow.com/questions/41118406/how-do-i-know-if-a-value-of-an-element-inside-an-array-was-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!