我有一个关于财产观察员的问题.下面是一些示例代码.我想要的是如果a.value被更改,属性Analysis.hasChanged将更新为true.有没有办法可以做到这一点?
class Number { var value: Double init(numberValue: Double) { self.value = NumberValue } } class Analysis { var a: Number var hasChanged = false init(inputNumber: Number) { self.a = inputNumber } } testNumber = Number(numberValue: 4) testAnalysis = Analysis(inputNumber: testNumber) print(testAnalysis.hasChanged) // will print "false" testNumber.value = 10 print(testAnalysis.hasChanged) // will still print "false", but I want it to print "true"
最后,我希望用户能够在他们的任何分析使用已更改的数字时收到通知,以便他们可以在选择时更新分析结果.
您可以使用Swift提供的内置属性观察器.每次设置新值时,都会调用didSet.您只需要将包含所需行为的闭包附加到Number类
class Number { var valueDidChangeClosure: (()->())? var value: Double { didSet { //won't call the valueDidChangeClosure //if the value was changed from 10 to 10 for example.. if oldValue != value { valueDidChangeClosure?() } } } init(numberValue: Double) { self.value = numberValue } } class Analysis { var a: Number var hasChanged = false init(inputNumber: Number) { self.a = inputNumber self.a.valueDidChangeClosure = { self.hasChanged = true } } } let testNumber = Number(numberValue: 4) let testAnalysis = Analysis(inputNumber: testNumber) print(testAnalysis.hasChanged) // will print "false" testNumber.value = 10 print(testAnalysis.hasChanged) // will print "true"