Hello everyone, Leo here. Today I want to share something I recently discovered, and you guessed right, the Swift Phantom Types in.

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 is MORE type-safe at compile time. With phantom types, you can restrict the code to make it safer for other developers and add extra information to your types. Therefore, more restrictions will lead to fewer programming errors, and better self-documenting code, and tests.

Swift Phantom Types Example

The example below explains how this applies 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 to 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 we gain that type check directly in compiler-time by transforming the brand into a phantom type. Check below:


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 is Ferrari and doesn't include a property to verify that

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

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

This is a runtime error in the Swift Phantom Type


So these are the basics Swift phantom types.
To get a better look, at this technique just look how phantom types are helpful in a full Functional Programming language like Haskell

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or just leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for the reading and… That’s all folks.

Credits: image