arraysswiftvaluechangelistener

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


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
    }
}

Solution

  • 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!")).