
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.