How to observer key value in swift 4?

What i am trying to do is observe the value change in name property.


class Person:NSObject {
   @objc var name: String
    let age: Double
    init(name: String, age: Double) {
        self.name = name
        self.age = age
    }


let _ = p.observe(\.name) { (object, change) in
          
      print("observed value is \(object.name)")
}
p.name = "Hello"



But, I cant observe the property change in the above code.What am i missing?

Accepted Answer

You don't say what "can't observe" means — compiler error, runtime error, observation not firing. However, you have a couple of problems in the above code:


1. You must declare the "name" property "dynamic". Otherwise, the assignment in line 14 bypasses the KVO notification mechanism, and your observer won't get triggered.


2. You must store the result of the "observe" call in line 10. The returned value is an object that represents the observation. If you discard the result, the observation is deallocated because nothing is keeping it alive, and you effectively remove the observation immediately after you attach it.

How to observer key value in swift 4?
 
 
Q