
Today I’m selling shovels. A treasure map. The equipment you need to tunnel through the Swift source code and mine out the nuggets of arcane knowledge reserved for C++ and compiler geeks.
There are three easy pieces of the Swift source code to understand. I’ll guide you through each layer, training you understand the common patterns and syntactic conventions. By the end, you’ll be confident to find your way through the Swift source code yourself without getting lost.
The standard library
The compiler
The runtime
We need a north star, something to hunt down as we traverse the layers of Swift’s internals. So today, we’re also going to find out precisely how the ubiquitous type(of:) function is implemented under the hood.
The hardest I’ve ever worked on an article was my (criminally underrated) COW2LLVM: The isKnownUniquelyReferenced Deep-Dive. I spent weeks spelunking through the Swift source code, with zero prior C++ knowledge, to hunt down how the classic copy-on-write optimisation really worked. It was fun. I got a meme out of it.
I’m going to use this baptism of fire to build you a template. A template that will save you from weeks of confusion while scouring the Swift source code to sate your curiosity. After this article, comprehending the Swift source code will feel a lot clearer. Perhaps we’ll get another meme. Let’s go.
type(of:) and the Swift Standard Library
type(of:) is a handy function while debugging. It returns the dynamic type of a function or property at runtime, even when it’s generic and unknowable at compile-time.
Let’s kick off by alt-clicking it in Xcode, to see the full declaration and documentation in the standard library:
With the Swift source code handy, we can download the source code from GitHub and search out this function declaration.
Builtins
We quickly find it inside swift/stdlib/public/core/Builtin.swift:
Builtins are internal constructs used throughout the standard library for ultra-optimised low-level performance (e.g. Bool being secretly represented by Builtin.Int1, a literal one or zero). This file of public Builtins promises “definitions that make elements of Builtin usable in real code without gobs of boilerplate”.
type(of:) is resolved by “a special case in the Swift type checker”. Let’s head down into the compiler to see what this means…
Subscribe to Jacob’s Tech Tavern for free to read ludicrously in-depth articles on iOS, Swift, tech, & indie projects in your inbox every week.
Paid subscribers get much more:
Read this article, plus all my Elite Hacks, my exclusive advanced content 🌟
Get my free articles 3 weeks before anyone else 🚀
Access my full Swift Concurrency course 🧵
Keep reading with a 7-day free trial
Subscribe to Jacob’s Tech Tavern to keep reading this post and get 7 days of free access to the full post archives.