使用的语言: 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
数组的值与以前不一样?
我知道filter
和sort
函数。我也知道如何使用didSet
以便我可以这样做
var doctors:[Doctor] = [] {
didSet {
// do something if `doctors` was changed
}
}
答案 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!")
)。