What’s new in Swift 4.2.1?

Yes! There appears to be such a thing, and it was silently shipped alongside Xcode 10’s first point-release, 10.1. Contrary to major releases, Swift 4.2.1’s release wasn’t accompanied by a blog post, nor was its entry added to the Swift changelog. Is there a reason for this all this mystery, or is the 4.2.1 really just so insignificant?

Pierpaolo Frasa must’ve been wondering the same thing, based on his recent post on the Swift forums:

My mac wants me to upgrade to Xcode 10.1, which will include Swift 4.2.1.
However, I can’t find any mention of that swift version either on the download page or in the changelog.


The list of resolved issues is rather short, with 8 compiler issues fixed, and just one problem resolved in the standard library. The highlights include: 

  • A fix for ambiguous compilation error messages like “Command CompileSwiftSources failed with a nonzero exit code”
  • The Bundle class’s init(for:) initializer now works consistently with Swift classes, not just Objective-C classes
  • Long file paths containing white space no longer cause build failures
  • A mutating method that returns Self on a value of protocol type can now successfully be invoked

Check out the “Swift Compiler” and “Swift Standard Library” sections in the Xcode release notes for a complete list of the changes, complete with code samples.


Making the case for Implicitly Unwrapped Optionals!

We’ve all seen them [Apple] do it: nonchalantly defining @IBOutlets as implicitly unwrapped optionals, by appending a ! to their type declarations. Isn’t this supposed to be a big no-no among True Swift Developers? You’d think so, since we’re told that stray exclamation points are often ominous precursors to pesky runtime crashes.

You could argue that declaring outlets as optional weak properties is preferable, as it sidesteps the runtime exception situation altogether. A reasonable rationale.

However, I’d like to challenge this nugget of common sense, and entertain the idea that using a ! here instead of ? is also acceptable.

A quick syntax refresher

In general, outlets form the glue that connect user interface elements – defined in Storyboards or XIBs – to their programmatic counterparts. If you’re the type to eschew Storyboards, here’s a quick syntax refresher:

@IBOutlet weak var profileButton: UIButton?

The @IBOutlet marker imposes no side-effects and can be omitted, if so desired. Personally, I like to have them there, as it makes them easier to call out afterward. The storyboard instantiates, manages and retains the actual button, so it suffices to hold a weak reference.

However, weak also makes the property optional, which is why we need the ? at the end.

The cost of using Optionals

?s are nice and safe, but their use comes at an undeniable cost. In order to be read, they need to be systematically unwrapped with if let or guard let. A minor inconvenience, for sure, but guard statements are prone to popping up all over the place, if not corralled consciously.

Catching mistakes in outlet wiring

Littering guard let statements up the wazoo makes you feel dirty too, I’m sure, but this can be overcome. What trips me up each time, however, is what happens if you hook up an outlet improperly (or simply forget to!).

  • Use an optional, and you’ll be scratching your head – like me – every time. The outlet will remain nil, your controller will initialize properly and you’ll be left clueless as to why something feels amiss.
  • Use an IUO!, and your app will crash 💥. This uncomfortable side-effect will provide an immediate cue, as the stack trace will reflect exactly which property is acting up. As a result, you’ll fix up your oversight swiftly, with no time wasted.

While I’m not quite sure if I should retroactively convert my existing outlet declarations, I started using ! a while ago and still feel good about it.

Favor crashes, over Optionals, in case of developer error

I agree we should strive toward a 100% crash-free rate, but for clear developer errors, I tend to favor a hard crash. I’ve found that selective use of IUO’s, and their resultant crashes, can actually provide a boost to developer productivity.

Truly, I’m not trying to be contrarian. A well placed ! just happens to be the fastest route to “success”, in this case.

P.S. You may get the impression that I use Storyboards, because I use outlets. I don’t 😎.


How to run SwiftLint autocorrect on each Git commit

SwiftLint was developed by the nice folks @realm. It’s a great open-source tool for establishing and enforcing a formal coding style in Swift. It runs on the command-line, but it can be hooked into Xcode directly too. It also has an “autocorrect” feature, which sweeps through your code and automatically fixes the most trivial violations (e.g., colon positioning, double white spaces, etc.). I created a Git commit hook which does exactly this, every time a team member makes changes.

The shell script itself is simple. Only files changed within the commit will be autocorrected. To prevent inadvertent file corrections, these changes are not automatically included in the current changeset. You will have the chance to review the corrections, and make a new commit to finalize them, or amend the previous commit.

git diff --cached --name-only | grep .swift | while read filename; do
    /usr/local/bin/swiftlint autocorrect --path "$filename"

Install this shell script under the .git/hooks directory of your Git repository. Be sure to name it pre-commit (no file extension).

This commit hook should work fine with whichever Git GUI tool you use, as well as the command-line of course.

Note that each team member has to repeat this installation individually. There is no way to automatically distribute git commit hooks.


Abolish Retain Cycles in Swift with a Single Unit Test

Can’t believe we’re still dealing with this in 2017? Well, that makes two of us. While retain cycles are easy to fix, they’re also hard to spot while eyeballing a codebase. Recently, I’ve found that a single unit test can provide solace. With just a few lines of code, it runs continuously as you make changes, all the while verifying you haven’t introduced any new memory leaks.

It’s a simple snippet, but I’ll walk you through it.

The test function makes use of XCTest’s asynchronous expectation system to pick up whether your class’s deinit function gets called. The subclassing trick you see there is needed because Swift doesn’t support reflection yet. The subclass tracks the deinit call by adding that deinitCalled closure.

The test works by allocating the instance on the main queue, while immediately deallocating it on the background queue. This triggers the deinit call, and the test succeeds.

If the test fails due to the 5-second timeout, this is your cue. You have just found a retain cycle! I’ve found it helps to run this test throughout the development process. The delta between code changes remains small enough to pick up where you forgot a [weak self] or [unowned self].

P.S. I was unable to figure out a way to make the test function generic, so I’ve been copy-pasting it around. I realize this is not ideal. However, I find it’s not a big deal because we’re dealing with test code, not actual app code.


Loading custom fonts programmatically in Swift 3

How do you include custom fonts in your application, if they don’t reside in the main bundle? In this case, loading them through the conventional PLIST method doesn’t work, and you will need to resort to CoreGraphics to register them programmatically.

Typefaces are an essential part of good design. On iOS, custom fonts can be added to apps through a somewhat convoluted process. Chris Ching has a good write-up on the topic, but in short: ensure the font files are properly included in your app’s target and declare them in your app’s Info.plist (“Fonts provided by application”). This works well in the straightforward case where the fonts are simply embedded into the main app bundle.

You quickly run into the limits of the PLIST-based registration method when they live outside of the main bundle, e.g. in a separate .framework. In this case, simply register the fonts using the older CoreGraphics APIs.

Marco Arment described the approach on his blog back in 2012, but the example code he lists is Objective-C. Fortunately, the Swift version of this code is much less cumbersome than its Obj-C counterpart, as less C-trickery is required:

// Load bundle which hosts the font files. Bundle has various ways of locating bundles.
// This one uses the bundle's identifier
guard let bundle = Bundle(identifier: "some.framework.identifier")
else { return }

// List the fonts by name and extension, relative to the bundle
let fonts = [
    bundle.url(forResource: "gotham_book", withExtension: "ttf"),
    bundle.url(forResource: "gotham_medium", withExtension: "ttf")

// Iterate over the resulting urls, filtering out nil-values with .flatMap()
for url in fonts.flatMap({ $0 }) {
  // Create a CGDataPRovider and a CGFont from the URL.
  // Register the font with the system.
    if let dataProvider = CGDataProvider(url: url as CFURL) {
        let font = CGFont(dataProvider)
        CTFontManagerRegisterGraphicsFont(font, nil)

Just make sure you don’t forget to remove any duplicate PLIST declarations, or your app will throw an exception at startup.


@sveinhal in the comments suggested this functional rewrite of the above code, which is way more succinct if that’s your cup of tea:

let fonts = [
bundle.url(forResource: "gotham_book", withExtension: "ttf"),
bundle.url(forResource: "gotham_medium", withExtension: "ttf"),

.flatMap { $0 }
.flatMap { CGDataProvider(url: $0 as CFURL) }
.forEach { CTFontManagerRegisterGraphicsFont($0, nil) }

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 (github.com/ReactiveCocoa/ReactiveSwift/blob/1.0.0/Sources/Property.swift):

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("https://httpbin.org/image/jpeg")

// 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: github.com/jarrroo/Blog-ConcatenatingSignalProducers

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 = users.map { user in
    return api.download(url: 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 = users.map { user in
    return api.download(url: 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

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 HTTPBin.org. 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, "https://httpbin.org/ip").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!