Using Dynamic keyword with Swift and ReactiveCocoa 2.0
We all know the importance of using work dynamic
in Objective-C. I am sure all of you must have used this keyword while working with Core Data. Stack Overflow answer summarizes it well that you will provide the implementation or getter/setter for property at runtime. If you are a purist, you can read it from Official Apple documentation.
Today I am going to talk about dynamic
keyword in terms of ReactiveCocoa and Swift. Usually using swift, developer puts an observer on properties which need to be observed. Say I have a property called firstName
. How do you observe any changes to it? Let's do one without dynamic
keyword.
var firstName = ""
// Add an observer.
RACObserve(target: self, keyPath: "firstName").subscribeNext { (name) in
// Won't work.
print("First name \(firstName)")
}
Unfortunately, this will not work. This was my first big mistake while converting an old Objective-C project to Swift. I didn't add the keyword dynamic
and the observer did not work. It took me a while to figure that out though. So if you want to observe any property in Swift using ReactiveCocoa
library, just declare it with a keyword dynamic
follows.
dynamic var firstName = ""
// Add an observer.
RACObserve(target: self, keyPath: "firstName").subscribeNext { (name) in
// Will work
print("First name \(firstName)")
}