Under The Bridge Under The Bridge

Category: Programming
Swift Witness For Sourcery

Yep, think we’ve outdone ourselves with the obscure title references this time. If you knew it was from Malachi 3:5, our congratulations!

What we’re talking about today is what you might have noticed when it was named Insanity, but these days is called Sourcery:

What is Sourcery?

Sourcery scans your source code, applies your personal templates and generates Swift code for you, allowing you to use meta-programming techniques to save time and decrease potential mistakes.

Using it offers many benefits:

  • Write less repetitive code and make it easy to adhere to DRY principle.
  • It allows you to create better code, one that would be hard to maintain without it, e.g. performing automatic property level difference in tests
  • Limits the risk of introducing human error when refactoring.
  • Sourcery doesn’t use runtime tricks, in fact, it allows you to leverage compiler, even more, creating more safety.
  • Immediate feedback: Sourcery features built-in daemon support, enabling you to write your templates in real-time side-by-side with generated code.

Sourcery is so meta that it is used to code-generate its boilerplate code

We’re pretty leery of tools like this in general as they end up being yet another cesspool of technical debt, but that this one is based on SourceKitten is interesting enough to at least pay some attention to it. And it’s catching a bit of buzz:

How to Automate Swift Boilerplate Code with Sourcery

Switching between our Android projects written in Java (or more recently, Kotlin) and iOS projects in Swift makes me sorely miss annotation processing. Annotations in Java can be used to generate common code and things that Swift developers would have to hand write. Hand written code has to be bug free and consistently updated and maintained. Things like implementing equals and parsing JSON typically require boilerplate code, unique enough that you cannot abstract it away.

Although Swift does not have annotation processing, we can get pretty close with Sourcery. Let’s take a look at how it all works in this quick Sourcery tutorial…

AutoEquatable and AutoHashable by Sourcery

I’m really interested in Sourcery, so I installed it in my one of repositories. In my case, I generated AutoEquatable and AutoHashable at first because I felt these implementations contain really a lot of boilerplate codes…

If I add a new property or a new API, it prevents a human error! Though it looks trivial, Sourcery uses a safe Hashable as I mentioned in Safe Hashable in Swift. Isn’t it cool?

The Magic of Sourcery

Sourcery is a code generation tool for Swift. It is particularly well suited for auto-generating code that is very repetitious; code most developers refer to as “boilerplate”. Some examples that come to mind:

  • Equatable implementations
  • Hashable implementations
  • struct initializers
  • Lens implementations …

Sourcery — Meta-programing in Swift

Think of the potential : you can basically generate all the boilerplates of your architecture be it CLEAN or VIPER, you can generate all the protocol implementation or even the Realm data object, or even a view based on the variables that are being declared ( Sourcery do support inline code generate ). A declarative view ! The sky is the limit !

Meta Programming Swift with Sourcery

#292: Metaprogramming with Sourcery 🔮

#294: Annotations with Sourcery 🔮

#295: Building an API client with Sourcery Key/Value Annotations 🔮

If you’re looking for a good project to try this out with, a decent set of VIPER templates would be eagerly welcomed. Let us know if you come up with something!

All About Errors

Here’s one to bookmark for reference: The veritably _definitive_ guide to

Error Handling in Swift

Regardless of your skill, handling errors is a common task for any developer. As developers we have complete control of the code we write and features we include, but despite our best efforts, we don’t control everything. We don’t control the values our users enter or whether our applications have access to the resources they need. In this post we’re going to look at how we can handle these situations by looking at error handling in Swift…

Pretty certain you’ll find something new here no matter what your skill level:

Up to now we didn’t even realize catch could take a where clause, huh. That’s what a couple decades of C++ will do to you, reflexively cringe in triggered terror at the mere thought of “exception”. But we’ll get through it — that bit about propagating back asynchronously looks particularly interesting!


Providing a unified Swift error API

Picking the right way of failing in Swift

Swiftier Swift, Swiftly

Everybody wants their Swift programs to run swiftier, right? In case you haven’t stumbled across it so far, The Canonical List Of Recommended Ways To Do That is found right in the Swift github repo:

Writing High-Performance Swift Code

So you should go read that at the first opportunity and keep an eye on edits too!

Follow that up with this excellently accessible talk:

Real World Swift Performance

Lots of things can make your application slow. In this talk we’re going to explore application performance from the bottom. Looking at the real world performance impact of Swift features (Protocols, Generics, Structs, and Classes) in the context of data parsing, mapping, and persistence, we will identify the key bottlenecks as well as the performance gains that Swift gives us…

Here’s a couple more illuminating posts on instruction level speediness:

Unowned or Weak? Lifetime and Performance

os_unfair_lock is the new synchronization hotness!

Mind you, it’s quite likely that for many of you the most compelling thing that springs to mind on reading the headline there is not swiftier execution, but swiftier compilation, amirite? Here’s some backgrounders and tips on that:

Profiling your Swift compilation times

Guarding Against Long Compiles

Speeding Up Slow Swift Build Times

Regarding Swift build time optimizations

After I read @nickoneill’s excellent post Speeding Up Slow Swift Build Times last week, it’s hard not to look at Swift code in a slightly different light. A single line of what could be considered clean code now raises a new question — should it be refactored to 9 lines to please the compiler? (see the nil coalescing operator example further down) What is more important? Concise code or compiler friendly code? Well, it depends on project size and developer frustration.

Before getting to some examples, let me first mention that going through log files manually is very time consuming. Someone came up with a terminal command to make it easier but I took it a step further and threw together an Xcode plugin

Also check out Swift build time optimizations — Part 2 for followup.

And you’re probably vaguely aware that XCTest does performance these days but haven’t adopted it wholeheartedly yet, right? Check out

measure(): How to optimize our slow code and adjust the baseline

XCTest makes performance testing extraordinarily easy: you give it a closure to run, and it will execute that code 10 times in a row. You’ll then get a report back of how long the call took on average, what the standard deviation was (how much variance there was between runs), and even how fast each of those 10 runs performed if you want the details…

Kinda handy to be able to get hard numbers for your refactoring efforts that easily, indeed.

Any other compilation or execution tips, tricks, and tradeoffs to share, Dear Readers?


Improving Swift compile times

Consistently Immutable

Here’s a good read for when you’re planning a data caching strategy for your Next Great Project:

Managing Consistency of Immutable Models

Immutable models have many advantages, but managing consistency can be difficult. At LinkedIn, we’ve open sourced two Swift libraries to help manage consistency and persistence of immutable models. Unlike Core Data, the API is non-blocking, exception-free, and scales well with large numbers of models and view controllers…

The natural reflex of course is Core Data, and these were their issues:

  • The first problem we ran into was stability…
  • The other issue we ran into was performance…
  • Another issue is there are no eviction strategies…
  • Another point was that migrations are necessary…
  • The final thing for us was scalability…
  • Even if we were to solve all of these problems, we didn’t like the programming model that Core Data provided. One of the things we didn’t like is that all the models were mutable, and they’re not thread-safe, so when you pass it to a different thread, you need to reread from the database…

We could nitpick over how serious these problems actually are if you know what you’re doing, but yeah that last one is kinda a deal. So what would a modern architecture look like, you ask?

What we really wanted to try was to use immutable models for all the data in our application. Immutable models have long been a cornerstone of functional programming languages, and with the introduction of Swift to iOS, I think that they’ve been pushing this idea of immutability. Swift has a bunch of “immutable by default” features, and personally, I’ve been learning a lot about immutability because of Swift. I’m going to list a few of the examples of why immutable models are beneficial:

We’ll assume you know those benefits already, but if not TL;DR they’re easier.

  • We wanted immutable, thread safe models for the reasons which I just went over.
  • We wanted consistency, so a change in one place would automatically be reflected elsewhere in the application.
  • We wanted non-blocking access on all reads and writes. There wouldn’t be any disk access on the main thread.
  • We wanted a simple eviction strategy. Looking at some of our peers, we saw that a lot of apps were using 200, 300, 400 megabytes of disk space, and ideally, for us, we wanted to limit it below 50 megabytes.
  • We want it to scale well. Again, as I said, we have hundreds of models and view controllers, and we wanted easy migrations. Actually, we wanted to write no migration code at all, ever.

To accomplish all these things we wrote RocketData.

RocketData is a caching and consistency solution for immutable models. It’s intended to replace Core Data or at least fulfill that role in an application. It’s written 100% in Swift, and we really like it…

Definitely read it all, but here’s the secret sauce:

The Consistency Manager, as I said, is truly the engine which drives everything. It’s an entirely separate open-source library that RocketData depends on. It’s written completely in Swift, and you can use it independently.

and here’s the executive summary:

Core Data Comparison

There is no tool which will solve every problem. For many use cases, we believe Rocket Data is a better option to Core Data because of the speed and stability guarantees as well as working with immutable instead of mutable models. However, Core Data is useful for other use cases, and it’s important to consider the differences before you make a decision for your app…

Always good to have options … and this looks like a pretty sweet one!


Speaking of options: Core Data or Realm

#35 Structs Alternative: Using Swift Protocols to Enhance Safety of Core Data Access

Introducing Plank: Immutable model generation for iOS

Make Collections Great Again

Pretty good chance you use UICollectionView pretty widely in your apps, right? And pretty much exactly the same chance you’d like some extra performance and enhanced reusability, no doubt? Ch-ch-check out

Open Sourcing IGListKit

Today, we are excited to announce that we’re open sourcing one of Instagram’s core frameworks: IGListKit. This framework powers how we take data from the server and turn it into fast and flexible lists.

To do this, we combined a familiar data-driven UICollectionView architecture with a state-of-the-art diffing algorithm. With this setup, we created a tool that lets engineers with varying levels of experience work quickly and safely on Instagram. Outside of Instagram, IGListKit can help anyone who is building lists to skip tedious and error-prone setup, and utilize one of the fastest diffing algorithms available for iOS…

Better Architectures

IGListKit reduces the chance of having “massive view controllers” by dividing responsibilities into multiple layers: the view controller, list adapter, section controller, and the cell.

This design has a positive side effect of building your lists with independent components, meaning you end up with reusable section controllers and cells. The result is a one-way data flow, where each component has no knowledge of its parent…


In Instagram, our data can change a lot. For example, new data arrives from the server each time you like a photo or you receive a direct message in real-time.

UICollectionView can handle all types of updates (deletes, reloads, moves, and inserts), but performing those updates without crashing can be a little tricky.

We built a lightning-fast diffing algorithm based on a paper published back in 1978 by Paul Heckel. This algorithm finds all of the possible updates that UICollectionView needs in linear time (that’s O(n))…

That’s a pretty serious level of win … especially if you’ve got some experience with that “little tricky” task of managing updates elegantly, in the same way that liquid nitrogen is a “little chilly”. So if you’ve got a big collection of data to manage, we wholeheartedly recommend you check that out!


And while you’re looking at libraries to make your UI nicer, check out this most excellent list:

39 Open Source Swift UI Libraries For iOS App Development

and of course there’s always

Awesome iOS: A curated list of awesome iOS libraries, including Objective-C and Swift Projects


The Case for Deprecating UITableView

IGListKit Reference

IGListKit Tutorial: Better UICollectionViews

IGListKit — Migrating an UITableView to IGListCollectionView

iOS Keeping data fresh in Buffer for iOS with AsyncDisplayKit, IGListKit & Pusher

TextureIntroducing Texture, a new home for AsyncDisplayKit

The Perfect 10

Yep, it’s that time of year again, where we all panic about getting new iOS features into our apps before ship date. Know the feeling? Thought so, yep. We’ve got a better excuse than usual this year though; this last month we’ve been settling into the electric city of Bangkok to work at agoda.com. Which we’d thoroughly recommend based on our experience so far; check out all the great jobs if you’re looking for an awesome gig! Any-ways, if you’re looking to get up to speed on iOS 10, here’s some great resources to put the pedal down:

iOS 10 Day by Day

This series has been a great resource for several OS versions now, and this year sure doesn’t look like a letdown so far:

Day 1 :: Messages

One of the new features was the ability for 3rd-party developers to create their own message extensions that can be used from within the Messages application… To demonstrate this exciting new extension type, we’ll take a look at a project that allows two players to play a simplified version of the popular game, Battleships,

Day 2 :: Thread Sanitizer

Xcode has shipped with a new debugging tool called the Thread Sanitizer which can help identify [threading] issues before you even notice them. We’ll create a simple application which enables us to deposit and withdraw money in $100 denominations…

Day 3 :: Xcode Source Editor Extensions

We’ll take a look at building our own extension that replaces ASCII characters with their Emoji equivalents…

Day 4 :: UIViewPropertyAnimator

To explore this new class, we’ll go through a few examples where we animate an image across the screen…

Of course, the Mother of All Tutorial Sites aka raywenderlich.com has their (6th!) annual opus proceeding nicely:

iOS 10 by Tutorials: First 6 Chapters Now Available!

Also note the iOS 10 + watchOS 2 bundle, and check out the latest tutorials/screencasts.

And one particular to finish off with; our entire career, we’ve had requests for voice dictation apps that we’ve always begged off with “Dude, that’s hard. And expensive.” Well, LOOK HOW EASY IT IS NOW:

Building a Speech-to-Text App Using Speech Framework in iOS 10

Truly, we live in the age of marvels.


A List of All Current iOS 10 UI Kits for Sketch

iOS 10 Sampler – A Set Of Examples For Many Of The New Features Added With The iOS 10 SDK

Getting Ready for ATS Enforcement in 2017

How to generate haptic feedback with UIFeedbackGenerator

Tutorial: Using iOS 10’s UIViewPropertyAnimator Class

Content app extensions in iOS 10

Enhance Your Apps With External Displays

Creating iMessage Apps Your Users Will Love

Improving our iOS Share Extension Installation Guide

Stylishly Swifty

Good talk and links here to keep you abreast of evolving Swift paradigms:

Swifty? Emerging patterns and idioms

Last Tuesday I gave a talk at Swift London called Swifty? looking at interesting patterns emerging from the community, as well as how Swift 3 will shape idiomatic code. You can see my slides on Speaker Deck.

The talk covered several topics, so I thought I’d link to some examples for those who want to learn more.

This is an even better post on namespacing:

Dear Erica: No-case Enums?

Dear Erica, Why would you create an enum with no cases?

This is such a great question! No-case enumerations represent a fairly obscure Swift “power tool”, and one that most developers are unaware of.

The answer, in a nutshell, is that they enable programmers to establish a mini-namespace with little overhead and an assurance that you can’t accidentally create type instances. Under their umbrella, you can group static members into namespaces, build singletons, create cohesive collections of functionality with a minimum surface eliminating freestanding functions, and in one outlier case provide services built around generic types…

And this is an interesting pattern for applying private type extensions which suits well our predisposition towards exposing only designated functionality, a position which is subject to some full and frank discourse over where they’re considering it as not just a style choice but an enforced language construct, if you’ve picked up on that brouhaha; if not, we’ll put an addendum here if/when something actionable happens. In the meantime, check out

Concealment design pattern in Swift

This article introduces a design pattern that I call Concealment, and demonstrates how to use the pattern in Swift code.


The Concealment pattern enables types to support novel, related functionality without adding nonessential members to their interface.


User-defined types can easily be overused in a codebase, giving more prominence to things than necessary. A common example is having a data model entity be involved with tangentially related concerns; such as validation checks, business rule processing, and display formatting. It is preferable to conceal the augmentation and usage of your types behind an API expressly built for a single responsibility, rather than expose those implementation details to all the types’ consumers…

Yep, we agree there; anything that reduces cognitive load is a Good Thing!


First Class Functions in Swift

10 Swift One Liners To Impress Your Friends

Enum Raw Values and Failable Initializers; Mixing Initializers

#257: Property Observers on Local Variables 🐤

How can I extend Array<MyStruct> with a custom function that should only work for these arrays?

Specifying function execution contexts

What are Protocols with Associated Types?; Type Erasure; Inception

Swift Type Aliases: Use Early and Often

#29 An alternative to if let and guard let

#32 Errorify String

Naming Things in Swift

Swift 3 Protocols

Refactoring to Clarity in Swift

Generic Protocols with Associated Type

Swift sequences: The art of being lazy

Swift Hashable

Bond: “A Swift binding framework” ; Bond Tutorial: Bindings in Swift

Express Yourself Swift Style

A Simple Undo/Redo Implementation in Swift

Loose coupling using default implementations in protocol extensions

SwiftTips: “A collection of Swift tips & tricks that I’ve shared on Twitter”

A Simple Undo/Redo Implementation in Swift

Standing on Guard

Here’s a question for discussion that will bring shivers of shared pain to the Swift programmer, no doubt:

Sneaky Swift Tricks: The fake Boolean

Moshe Berman writes, “If I’ve got a bunch of chained guard let statements, how can I diagnose which condition failed, short of breaking apart my guard let into multiple statements? Given this example:

How can I tell which of the 4 let statements was the one that failed and invoked the else block?”

How, indeed? TL;DR There isn’t a really good way. Bah.

However, besides the linked article there’s an active discussion at the Stack Overflow question, and we’d suggest checking on them to see if anything that suits you has shown up, and if not pick up some more Swifty tricks along the way. The one we like the best so far is this gist from AfricanSwift defing the =∅ (null check) debug operator:

If you have a better suggestion, that Stack Overflow question is waiting!

Tip: Swift Common Initializer Pattern

Here’s a handy tip for reducing duplication and/or frustration with your initializers:

Common Initializer Patterns in Swift

Swift has a very well thought-out initializer system in place. With options such as designated and convenience initializers, one must ensure all properties have values since the compiler will make sure of it. Take a look at my other post for more details.

… Your first thought may be: why not wrap it in a function and call the function from both initializers. Nope. Can’t do that because you cannot reference “self” for the method call before calling “super.init“, and you can’t call the method after initialization either until you’ve initialized all properties – catch 22:

So you end up either tedious and violating DRY, or using var/lazy and violating immutability, yes, we find that niggling on a fairly regular basis. Skipping past the narrative (follow the link if you wish) Here Is The Solution:


Wow, nice! Solves the redundant code problem while still abiding by the initialization rules. It’s using a static function to initialize the properties, which indeed can be called before the class is initialized (since it’s static and not using self).

Secondly, it’s returning a tuple to initialize multiple properties at once. That’s cool too! And for the sugar on top, it’s using a “typealias” like “My” or “I” to keep the static calls short.

We like it! Very Swifty feeling, isn’t it?

h/t: This Week In Swift!

For another interesting initialization pattern, check out

Swift: Configuring a Constant Using Shorthand Argument Names

It’s a common pattern in Swift (and a really nice one!) to configure constants right when they are initialized in a closure vs later on in a viewDidLoad or another such method … ’ve always found it kind of awkward to name another UIView in the closure. Now there is a “purpleView” and a “view”. Should “view” actually be named “purpleView” also? I haven’t figured out a good solution for the naming problem here. So I was super excited to see the tweet that uses $0 instead of bothering to name the variable!

Not quite sure whether we actually prefer this, but it is more concise. Also check out the Configurable extension from the comments!

Tip: Adding Fields To Interface Builder

Here’s a neat trick that might have never occurred to you — it didn’t to us, anyways:

How to use Xcode to set a text field’s maximum length, Visual Studio-style

There’s the [Visual Studio] GUI builder way…

  1. Select the text box.
  2. Set its MaxLength property in the Properties pane.

… when developing Objective-C and Swift applications in Xcode:

There isn’t a GUI builder way — just a code way, and it’s a little more work than it needs to be…

… That’s a lot of work. Isn’t there a way we can get a “max length” property for text fields, like the .NET people?

And why, yes. Yes, there is! The trick is simply to create an @IBInspectable extension on UITextField:

Swift extensions let you add new functionality to existing classes, structs, enumerations, and protocols. We’re using an extension to UITextField to add two things:

maxLength, a property that lets the programmer set and get the maximum length of a text field, and

limitLength, a method called whenever the contents of a text field are changed, and limits the number of characters in that text field.

Look over the rest of the article and download the sample project for an explanation of the techniques used here. Mighty handy for extending built-in types if you like doing your interface work graphically in Interface Builder … and who doesn’t?