Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to observe a change in a class's property from another class

Tags:

ios

swift

I've got a question on property observers. There's some example code below. What I want is for the property Analysis.hasChanged to be updated to true if a.value is changed. Is there a way I can do this?

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"

In the end, I want the user to be able to be notified if any of their analyses use numbers that have been changed so that they can update the results of the analyses if they choose.

like image 294
Logan Avatar asked Jan 26 '17 19:01

Logan


1 Answers

You can use the built-in property observers provided by Swift. Every time you set a new value, the didSet will be called. You just need to attach the closure, wrapping the desired behaviour, to the Number class

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"
like image 195
Denislava Shentova Avatar answered Sep 28 '22 09:09

Denislava Shentova