Filling the KVO gap in Swift with ReactiveCocoa

How do you do Key-Value Observing in Swift? Can you? And what about just using Objective-C's native KVO mechanism? What follows is a gentle introduction to ReactiveCocoa's unsung hero of property observation: Property (and MutableProperty). 

Matt Thompson explained the ins and outs of KVO in exasperating detail in 2013 for NSHipster. In summary, let's just say it's a messy Objective-C API, which still happens to work in Swift today. Aside from the occasions where you can't do without (NSProgress anyone?), I would advise against using it. Its complexity makes it prone to bugs. But Swift doesn't offer a native equivalent, you say...

I hear you, but suppose you could simply do something like this, to listen for changes and reload a table view in response, picking up any new items:

override func viewDidLoad() {

    viewModel.drafts.signal.observeValues { [weak self] drafts in

Meet ReactiveSwift Properties

I would be omitting an important tidbit about Swift's native observation capabilities, if I neglected to mention the didSet and willSet property observers. With enough boilerplate code, you can definitely cobble together something akin to KVO. You could, for instance, listen to the property changes yourself with didSet and re-dispatch these events over a delegate. Purists will prefer this approach, because no magic is involved, and no third-party libraries are required.

However, ReactiveSwift aims to encapsulate all this complexity by means of a singular concept, called Property. Simple, because at its core, Property is merely a value box, with a means to notify others of its changes. Here's the pared-down protocol, taken from the 1.0 release of ReactiveSwift (

public protocol PropertyProtocol: class, BindingSourceProtocol {
	associatedtype Value

	var value: Value { get }
	var producer: SignalProducer<Value, NoError> { get }
	var signal: Signal<Value, NoError> { get }

The producer and signal properties are the actual observables you subscribe to for changes. Why the distinction? The RxJS README has a nice summary:

"Cold observables start running upon subscription, i.e., the observable sequence only starts pushing values to the observers when Subscribe is called. Values are also not shared among subscribers. This is different from hot observables such as mouse move events or stock tickers which are already producing values even before a subscription is active."

When applied to ReactiveSwift, cold observables correspond to signal producers, while hot signals are represented by "regular" signals. In the context of properties, this boils down to:

  • Starting the producer will emit the property's initial value, as well as any subsequent changes;
  • Observing the signal will only emit the values changed after the observation was started.


The concrete implementations of PropertyProtocol are contained by the classes Property and MutableProperty. Generally, you'll be using the mutable variant, since it allows you change the property's underlying value, thus triggering change notifications. The easiest way is to forego optionals and use let constants instead:

// Defining the property
let avatarUrl = MutableProperty("")

// Setting the property's value
avatarUrl.value = "..."

// Listening for changes, without the initial value
avatarUrl.signal.observeValues { url in

// Listening for changes, including the initial value
avatarUrl.producer.startWithValues { url in

Data binding

Data binding is a means of tying properties to UI components, so that the component updates itself whenever the property changes. Contrary to AppKit, iOS' UIKit has no notion of data binding. ReactiveCocoa exposes data binding through a single custom property: a less-than sign followed by a tilde.


Its shape emphasizes the binding's unidirectionality. The following example clearly expresses the fact that the artist name is being set on the artist label's text property whenever it changes, not the other way around:

// Hook up bindings in your controller's viewDidLoad()
func viewDidLoad() {
    artistLabel.reactive.text <~ viewModel.artistName

// Example implementation of this viewModel (details omitted for brevity)
class ViewModel {
    let artistName = MutableProperty<String?>(nil)

Data binding is a declarative way to express relationships between data and UI components. It reduces the cognitive overhead of manually assigning values. Code locality is also improved, as this approach centers binding logic into a single place. 

ReactiveCocoa & ReactiveSwift

What's the difference? With ReactiveCocoa 5, the core team decided to split up the codebase, in order to more clearly delineate each component's responsibility and scope. This division also allows framework users to more easily cherrypick which modules they need in their projects.

  • ReactiveSwift: The new kid on the block. This is a pure-Swift implementation of the reactive API. It provides all the nuts and bolts, including Signals, SignalProducers, Properties, Actions and Bindings.
  • ReactiveObjC: ReactiveSwift's Objective-C-based sibling. This is essentially ReactiveCocoa 2.0 and remains in maintenance mode.
  • ReactiveCocoa: The connecting piece between UIKit and ReactiveSwift. It provides all of the reactive extensions for UIKit components and exposes binding targets for them. It also introduces Triggers, a means for converting Objective-C selectors into signals. You can also wrap good ol' ObjC KVO with signals, so they can be interspersed with ReactiveSwift signals and producers.
  • ReactiveObjCBridge: Bridges the ReactiveCocoa 2.0 API with the ReactiveSwift API, so ReactiveObjC remains accessible from Swift, enabling interoperability with old code.

Why Swift is making me feel blue

I'm just about blue in the face complaining about it, too. So bear with me if you've heard all this before. I promise I'll stop ranting after this post, and move on to happier topics ;-).

Slow as molasses

I wrote this post while waiting for Xcode to finish compiling

I realize this may be caused by a combination of issues. Perhaps the Swift compiler is not optimized yet. Perhaps it's just the generally awful state of the Xcode toolchain. Whichever the culprit, the end result remains equally as enervating... I am referring to Swift's complete and utter slowness with regards to code compilation.

If you've done any serious Swift development of late, you know that incremental Swift compilation is a lie. All but the most trivial changes trigger complete rebuilds, resulting in insane waiting times between builds. Apple supposedly set out to resolve this issue with Xcode 8.2.1, but I believe they merely put out a lopsided mitigation in lieu of an actual fix.

With no real insight into how Xcode determines the scope of the required recompilation, it appears Xcode gets into trouble as soon as you alter the external interface of a (any) source file. This includes adding new functions, modifying existing function signatures, altering the inheritance chain and the like (which has to be 75% of the time, right!).

I have been struggling with this particular rough patch in Swift for the better part of a year and resulting frustration has even driven me to reconsider Objective-C. Folly, I know! On a more serious note, though: the current compiler/toolchain performance is a severely limiting factor on my overall coding productivity. Stuff takes longer to get done. My MacBook's fans are ablaze all day long. And I drift off to Facebook and Twitter in between builds and struggle to pick up where I left off 😫🤕.

This is not to say that I don't absolutely prefer Swift over Objective-C (and any other higher-level language, for that matter). I love the enthusiastic community surrounding it. The general direction the open-source project is taking the language is equally as encouraging. But its newly-fangled-ness makes the fledgling language pretty rough around the edges. Perhaps the 1.0 moniker was bestowed on it too soon? Perhaps it's my fault for being an early adopter? Maybe. All I know is that this part of Swift still needs quite a bit of work. I just hope enough of the smart minds in the Swift community are looking as much inward, as they are forward.

SourceKit hell

SourceKitService is the memory-hungry background process which powers Xcode's syntax highlighting and code analysis. Even though it has dramatically improved since Swift 2, its performance remains a big issue. Too often, code will be marked as erroneous or no syntax highlighting will be available at all. Despite being decoupled at the process-level, Xcode still depends strongly on SourceKitService. Autocompletion and ⌘-click navigation, for instance, are severely impacted by SourceKit bugs. A rebuild often resolves the bug, albeit terribly slowly, because of my earlier gripe...

As much as I love to bask in the glory that is Swift's newness and road to world domination, I also need things to work, and waiting around for a computer isn't really my idea of "working". But I -- and no doubt many others -- will continue to put up with it.

Because we believe in the Swift project, right?

How to concatenate SignalProducers with ReactiveCocoa 5

ReactiveCocoa, and functional programming frameworks in general, are sometimes frowned upon for their steep learning curve. This is an undeniable, yet not insurmountable fact. The nice thing is that ReactiveCocoa is opt-in, and it doesn’t have to be all-encompassing. You can take advantage of the bits you like, without impacting the rest of your code.

Development stack: Swift 3, ReactiveSwift 1 (part of ReactiveCocoa 5)
Example project on Github:

Composition is King

Perhaps one of the most important features of ReactiveCocoa is its opinionated stance on composition. It’s expressed in countless APIs and is spread across the whole framework. While there is clearly a lot more to be said on the subject, let’s focus on SignalProducers for the time being.

Composing SignalProducers often involves the .flatMap() or then() operators, but sometimes it’s more efficient to first collect a list of producers and concatenate them in one go. Consider the following hypothetical example:

let users:[User]
let api:APIClient

// getAvatars's type will be inferred to [SignalProducer<UIImage,APIError>] by
// the Swift compiler
let getAvatars = { user in
    return user.avatarUrl)

getAvatars now holds a list of SignalProducers that each will go out and fetch the avatar images, as soon as the producer is started. But how do we actually queue them all up in one fell swoop?

It turns out one of SignalProducer‘s initializers conveniently accepts a list of producers (excerpt from ReactiveSwift’s interface):

/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
/// - parameters:
/// - values: A sequence of values that a `Signal` will send as separate
///           `value` events and then complete.
public init<S : Sequence where S.Iterator.Element == Value>(values: S)

When applied to our getAvatars example, it translates into:

let users:[User]
let api:APIClient

let getAvatars = { user in
    return user.avatarUrl)
// Ick. Y no type inference?!
let producers:SignalProducer<SignalProducer<UIImage,APIError>, APIError> = SignalProducer(values: getAvatars)

producers.startWithResult { result in
    // Handle results however appropriate

As you can see, the values: initializer creates a (fairly scary-looking) “producer of producers”. Due to the current state of Swift, the compiler expects an explicit type declaration here. I’m assuming this behavior is actually a bug, though I haven’t put in the time to verify that [yet].

Bummer.. Thankfully, we can extend SignalProducer like so:

extension SignalProducer {
    static func flatten(_ strategy: FlattenStrategy, producers:[SignalProducer<Value,Error>]) -> SignalProducer<Value,Error> {
        let p = SignalProducer<SignalProducer<Value,Error>,Error>(values: producers)
        return p.flatten(strategy)

This extension encapsulates all the explicit typing nonsense by referencing the generic value and error types, so you don’t have to. We can now reformulate our example to be much more concise:

let getAvatars = ...

  .flatten(.concat, producers: getAvatars)
  .flatMap(.concat) { avatar in
    return processAvatar(avatar) // some kind of image processing
  .startWithResult { result in
    switch result {
      case let .failure(error): // do something with errors
      case let .success(avatar): // do something with the UIImage avatars

As expected, the getAvatar(..) methods will be called in succession, effectively running the requests in a serial queue.

10 awesome Swift features for you diehard Swift naysayers

After being a die-hard Swift holdout (and fervent Objective-C defender), I dove head first into my first Swift-only project several months ago. The project was fairly new with only a few thousand lines of code, so it was the perfect opportunity to finally give Swift the honest chance it deserves.

I had many non-reconcilable issues with Swift's initial release syntax and tooling. It was simply too rough and unfinished. In recent months, however, notably with the 2.x line of releases, Swift has sincerely grown up and can finally be considered a "real" programming language. If you're still stubbornly on the Objective-C side of the fence - I get it - but consider this: Objective-C is over 30 years old; ancient by anyone's standards. And for all of Swift's kinks, it's as clean a break from the past as is possible for the Apple platform. Recent incarnations of the language drop all of Objective-C's antiquated C heritage and expresses itself through a clear, safe and reasonably terse syntax.

But why fix what ain't broke?

This is a legitimate question and there's no need to demonize Objective-C's dynamism. It has served developers well for over thirty years. So why has it been villainized of late? Clearly, there should still be a place in this world for dynamic languages like Objective-C. On the other hand, a whole class of bugs can be avoided by foregoing dynamism, while enabling compiler optimizations previously deemed impossible. Also, the dynamism/strictness debate seems to be seasonal, alternating from one to the other from time to time. I have come around and I'm now firmly pro-type safety. Inspired by functional programming, Swift also strongly encourages immutability, which in my opinion, leads to code which is easier to write and understand.

In the end, it's up to you to decide whether Swift can replace Objective-C in your app development toolbox. One thing is clear though: Apple has ceased improving Objective-C for its own sake. Instead, improvements are merely applied to serve better interoperability with Swift (like, recently, nullability and lightweight generics). All of Apple's future development efforts will be focused on Swift. It's not a bad idea to follow their lead, and now may not be such a bad time to start if you haven't already, as Apple has promised less code breakage in the post-Swift 3 timeframe.

Here are 10 Swift perks you can't take advantage of if you decide to stick with Objective-C:

  1. Default implementation with protocol extensions
  2. Easy early returns with guard let
  3. More fluent APIs with trailing closures
  4. Order-independent function parameters with default values (update)
  5. Single-line closure declaration by using order-based parameter names
  6. Easy namespacing with structs enums (update)
  7. Protocol implementation in extensions
  8. Defining multiple classes / structs / protocols / extensions in a single .swift file
  9. Auto-generated init parameters in structs
  10. Built-in support for lazy instance variables

I only have time for the first three today, so let's get to it.

1. Default implementation with protocol extensions

Protocols ("interfaces" in other languages) are "insanely great". They're one of the building blocks of software architecture and have a place in every software project. Swift's protocols are even more powerful when they are combined with extensions. They are effectively what Rubyists call mixins: bits of behavior that can be added to classes without the need for subclassing. The following example was taken from my open source toolkit for the Coordinator design pattern, called CoordinatorKit.

Consider the Coordinator and ComposableCoordinator protocols:

public protocol Coordinator: class {
    func start()

public protocol ComposableCoordinator: Coordinator {
    var childCoordinators: [Coordinator] { get set }

They simply define that any Coordinator should at least have a start() method and that any Coordinator that fits into a hierarchy of coordinators should at least expose an array of its children.

A common operation in this model would be to look up a child coordinator by its type, and return it. The following method accomplishes this recurring bit of functionality:

func findChildCoordinator<T>(type: T.Type) -> T?

To avoid having to re-implement this all over the place (or having to define it as a public function), one way to go about it would be to create an abstract superclass which implements ComposableCoordinator and implement it there. While is works, it's a bit of a code smell, because Swift has no official notion of 'abstract' classes. This enforced subclassing is also limiting to the user, because like most object-oriented programming languages, Swift only allows single inheritance. The Swift-way would be to declare this recurring functionality in a protocol extension:

extension ComposableCoordinator {
    public func findChildCoordinator<T>(type: T.Type) -> T? {
        return childCoordinators.filter({ (coordinator) -> Bool in
            return coordinator is T
        }).first as? T

Any class which conforms to ComposableCoordinator will get the findChildCoordinator<T>() method for free, without the need for subclassing. Because this is protocol-oriented, you can mix in any amount of functionality, in a way that doesn't rely on convention and is supported by the language and tooling. Xcode will autocomplete this method signature on any compliant class, provided SourceKit isn't crashing, of course (wink wink).

2. Easy early returns with guard let

The handling of optionals is very prominent in Swift because it's one of the ways the language guarantees safety. Objective-C, in contrast, provides no safeguards around the handling of nil values, potentially leading to various types of nil-related crashes. While being so explicit about optional values increases safety, it adds programmer overhead in the form of countless optional unwrapping if let statements. Thankfully, Apple resolved the if let-nesting issue with the introduction of compound if let statements, but what is this guard let thing then?

Oftentimes, multiple optional values need to be unwrapped as a means of validation before proceeding execution of a method. To prevent many repetitions of if let (nested or not), you can employ guard let at the beginning of a scope to unwrap optionals and force an early return (and additionally throw an error or do some other kind of handling). After this point, you can simply pretend optionals don't exist.

Consider this contrived example for some hypothetical sign-in code:

func login(usernameText:String?, passwordText:String?, captchaText:String?, completion:(error:NSError?)->()) {
    // Catch empty values and call closure with an error
    guard let username = usernameText, password = passwordText, captcha = captchaText
    else {
        let error = // some error
        completion(error: error)

    // regular login handling continues here

Optional unwrapping is conveniently focused in one place, without the need for nesting or logic branching.

3. More fluent APIs with trailing closures

Since the introduction of Objective-C blocks ("closures" in Swift), Apple has been adding them to its APIs wherever it makes sense. Completion closures are by far the most common. For example:

UIView.animateWithDuration(1, animations: {
    // Animation code

With Swift, whenever a closure is the last parameter, you can use this more compact notation:

UIView.animationWithDuration(1) {
    // Animation code

Superficial, I know, but it turns closures into first-class citizens. They fit in more naturally with the rest of the language and reduce visual clutter by eliminating the closing parentheses.


Header image courtesy of Tristan Ferne on Flickr (CC BY 2.0).


I would like to thank the following people for responding constructively to my write-up:

On reorderable parameters: Kyro38 on /r/swift correctly pointed out that this feature has actually been removed in Swift 3.. I guess it was nice while it lasted. You can find the Swift Evolution Proposal here. If you've been using this feature (like me), it won't hurt to prepare your code for this upcoming change.

On using structs for namespacing: @boolkybear suggested on Twitter that using enums would be better because they can't be instantiated, contrary to structs. True that!

Stubbing network requests with fixtures

Developing client and server networking code in lockstep with OHHTTPStubs fixtures. This Swift/Obj-C library provides an easy way to hook into the iOS HTTP networking stack to serve local responses for offline integration and unit testing.

You'd be hard-pressed to find an iOS project that doesn't contain networking code. Saving user data, requesting app content and storing away analytics are just a selection of the activities that require network access.

Developing against the live API is clearly the most desirable, but what if it's still being developed in parallel? Or down for some reason?

Until recently, I would create an alternative implementation and manually stub out the expected API behavior in code. I'd write my unit tests and also inject the stubbed interface into the actual application so I could get ahead with the UI. This approach is uncomplicated and works reasonably well.

Where it breaks down for me is its manual nature. With each revision of the API interface, the stub needs to follow along. And as the stub's implementation expands, this repetitive process grows all the more cumbersome.

OHHTTPStubs' roots lie in Objective-C, but it is perfectly Swift-compatible. When enabled, HTTP responses are intercepted and replaced with predefined fixtures. These typically contain sample output for API calls in JSON, though they can be supplied in any text format.

I have created a basic demo project to demonstrate how this library could be used in your next project. It's all up on GitHub, so feel free to clone/fork it and follow along.

It's an iPhone app which uses Alamofire to call the /ip endpoint of A tap on either button will call the web service and display the response in a UIAlertController.

Here's the implementation for getIPAddress() (AddressHTTPService.swift, line 14):

func getIPAddress(callback: (String) -> ()) {
    Alamofire.request(.GET, "").responseJSON { response in
        if let JSON = response.result.value, origin = JSON["origin"] {
            callback(origin as! String)

In the same file, I defined a separate class to hold the logic for loading and unloading the fixtures. You're free to choose where you put this code, as it doesn't particularly matter. Wrapping it in a separate class is also optional.

class AddressHTTPServiceStubs {
    static func loadStubs() {
        stub(isPath("/ip")) { request in
            let stubPath = OHPathForFile("ip_response.json", AddressHTTPService.self)
            return fixture(stubPath!, headers: ["Content-Type":"application/json"])

    static func unloadStubs() {

To enable the stubs in your application or tests, simply call the loadStubs() method:

@IBAction func getIpViaStub(sender: UIButton) {

The library comes with a couple of built-in request matchers. However, the raw request object is accessible, so more granular filtering shouldn't be too challenging.

That's it!

As you can see it's fairly easy to put stubbed responses in place for offline or unit testing. It's mostly a matter of writing a filter to direct OHHTTPStubs to the correct fixture file, and updating the canned responses whenever an associated API changes.


Feature image courtesy of Radomir Cernoch, who generously licensed this photo as Attribution-ShareAlike 2.0 Generic. Thank you!