我试图解决的问题是我想doCommonUpdate
在一个值更改时接到一个电话,或者如果两个值同时更改时接到一个电话。这样做会产生递归,因为如果任何一个值发生变化,它didSet
每次都会调用。示例设置,我的更多参与:
class Person {
var first: String = "" {
didSet {
updateValues(first: first, last: last)
}
}
var last: String = "" {
didSet {
updateValues(first: first, last: last)
}
}
init() {}
init(first: String, last: String) {
self.first = first
self.last = last
}
// also want to set both at the same time.
func updateValues(first: String, last: String) {
// self.first = first // causes recursion.
// self.last = last
doCommonSetup(first: first, last: last)
}
func doCommonSetup(first: String, last: String) {
print(first, last)
}
}
let l = Person()
l.first = "Betty"
l.last = "Rubble"
_ = Person(first: "Wilma", last: "Flintstone")
> Betty
> Betty Rubble
注意 由于注释掉的行,Wilma 不会打印。
我的解决方案是将所有这些变量移动到一个单独的结构中。这种方法解决了这个问题,并具有创建另一个有助于意义的分组的附带好处。我们仍然会得到doCommonSetup
两个值独立变化以及两个值同时变化的时间。
class Person2 {
struct Name {
let first: String
let last: String
}
var name: Name
init() {
name = Name(first: "", last: "")
}
init(first: String, last: String) {
name = Name(first: first, last: last)
updateValues(name: name)
}
var first: String = "" {
didSet {
name = Name(first: first, last: self.last)
updateValues(name: name)
}
}
var last: String = "" {
didSet {
name = Name(first: self.first, last: last)
updateValues(name: name)
}
}
// also want to set both at the same time.
func updateValues(name: Name) {
self.name = name
doCommonSetup(name: name)
}
func doCommonSetup(name: Name) {
print(name.first, name.last)
}
}
let p = Person2()
p.first = "Barney"
p.last = "Rubble"
_ = Person2(first: "Fred", last: "Flintstone")
> Barney
> Barney Rubble
> Fred Flintstone