NEW: Learn SwiftUI with my free YouTube video series! >>

What is key-value observing?

Swift version: 5.0

Paul Hudson    @twostraws   

Key-value observing is the ability for Swift to attach code to variables, so that whenever the variable is changed the code runs. It’s similar to property observers (willSet and didSet ), except KVO is for adding observers outside of the type definition.

KVO isn’t terribly nice in pure Swift code, because it relies on the Objective-C runtime – you need to use @objc classes that inherit from NSObject, then mark each of your properties with @objc dynamic.

For example, we could create a Person class like this:

@objc class Person: NSObject {
    @objc dynamic var name = "Taylor Swift"
}

let taylor = Person()

You could then observe that user’s name changing like this:

taylor.observe(\Person.name, options: .new) { person, change in
    print("I'm now called \(person.name)")
}

That asks Swift to watch for new values coming in, then prints the person’s name as soon as the new value is set.

To try it out, just change the person’s name to something else:

taylor.name = "Justin Bieber"

That will print “I’m now called Justin Bieber.”

Although KVO is unpleasant in pure Swift code, it’s better when working with Apple’s own APIs – they are all automatically both @objc and dynamic because they are written in Objective-C.

However, one warning: even though large parts of UIKit might work with KVO, this is a coincidence rather than a promise – Apple make no guarantees about UIKit remaining KVO-compatible in the future.

SPONSOR Meet the new Instabug – more than just bug reporting! We help you build better apps and minimize your debugging time. With each bug report, we automatically capture details like network requests, repro steps, and session details. Get real-time crash reports with stack trace details and session data to help you catch and fix issues easily. And with our customizable in-app surveys, you’ll gather insightful user feedback and much more. Instabug is the fastest and easiest way to release with confidence. Start your free trial now! Start your free trial now!

Available from iOS 8.0 – learn more in my book Swift Design Patterns

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.5/5

Click here to visit the Hacking with Swift store >>