Phantom Types in Swift

Subscribe to my newsletter and never miss my upcoming articles

Hello everyone, Leo Here.

Today I want to share something I discovered recently, and you guessed right is the Phantom Types in swift.

The phantom type definition is a technique to create a compile-time guarantee that a given piece of data will always match our requirements. In others, a way to Swift be MORE type safe at compile time. With phantom types you can restrict the code to make it more safe to other developers and also you can add extra information to your types. Therefore, more restrictions will lead to less programming errors, better self-documenting code and tests.

The example below we will explain how this apply to a car dealer.

enum Brand {
    case ferrari
    case ford

struct Car {
    var model: String = ""
    var brand: Brand?

var car1 = Car()
var car2 = Car()

Imagine that you will have different sell routines for each one of your Cars Brands. One option is include an attribute of enum type CarBrand and inside the CarBrand you'll have cases of each brand. Of course, is one way to get that, but that way you will have to make sure every time you call sell with a Switch statement. For example :

func sell(car: Car) {
    //put your enum brand logic here

But transforming the brand in a phantom type we gain that type check directly in compiler-time.

enum Ferrari {}
enum Fiat {}

struct Car<Brand> {
    var model: String = ""

var car1 = Car<Ferrari>()
var car2 = Car<Fiat>()

func sell(car: Car<Ferrari>) {
    //now you're sure about the car type and doesn't include a property to verify that

func sell(car: Car<Fiat>) {


Other perk that you gain using phantom types is that the two car above can't be compared anymore, because the compiler will tell this:

Captura de Tela 2020-06-24 às 12.42.18.png

So this is the basic of basic of basic of phantom types in Swift. To get a better look, about this technique just look how phantom types are useful in a full Functional Programming language like Haskell.

Thanks for the reading and... That's all folks!

No Comments Yet