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 firtsName. How do I 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)")                
}

This will work, right? No. This was my first big mistake while converting old Objective-C project to Swift. I didn't add the keyword dynamic and 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 keyword dynamic like follows.

dynamic var firstName = ""
// Add an observer.
RACObserve(target: self, keyPath: "firstName").subscribeNext { (name) in
    // Will work
    print("First name \(firstName)")                
}

Jayesh Kawli

I am a web and mobile developer working at Wayfair in Boston, MA. I come to learn so many things during course of life and I write about things which helped me and feel like they can help others too.

Subscribe to Fresh Beginning

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!