Jack Morris
Scope Your Magic
23 Feb 2020

Swift is a language where it's possible to write quite a bit of magic. What do I mean by that?

I usually use the term to describe constructs that appear to be built-in, but are actually built by us. Swift's support for things like extensions on standard library types, property wrappers, first-class functions, and function builders, make it possible to abstract away a large amount of boilerplate, replacing it with something far more concise (which may even be masquerading as a language keyword).

When used appropriately, these can be hugely useful; I recently wrote about how we can concisely express predicates using key paths in Swift 5.2. I'd definitely call that magic, albeit in a positive sense.

recipes.filter(\.isAttempted && \.difficulty < 2).map(\.name)
// 🧙‍♂️

However it's dangerous to allow such tricks to leak throughout your entire codebase. For new members of your team, having to ramp up on a new project is hard enough as it is without having to learn your flavour of Swift from the inside out. For the above, even knowing where these overloads are defined is tricky. You can probably control-click on && (if Xcode is in a good mood), but you may not be aware of what is built in and what is magic. The lines start to blur.

One trick that I've found useful is to ensure that all such magic is well encapsulated into individual modules. There's nothing wrong with using small modules in your project (as long as it doesn't start to noticeably increase build times), and doing so makes it obvious when you're importing some extra functionality into a file.

// _Only_ imported when required.
import Predicates

// Supplies some context for this syntax.
recipes.filter(\.isAttempted && \.difficulty < 2).map(\.name)

It also makes it trivial to survey where you're using a piece of functionality at a glance with a simple search for import Predicates. A few months down the line, maybe you're only making use of it in one place? It could be worth cleaning up, falling back to something built in to improve readability; it's probably not worth forcing readers to learn a new piece of magic when it's only used once.