Phantom Types in Swift

Karthik Shiva
2 min readJan 21, 2022

--

A Phantom type is just a generic type which is never used inside an object. So, why does it exist then? Type safety. Lets find out how.

In the below example, we have an user, product and a shopping cart. Both the user and the product have an id property of the same data type Int64. Even though they have the same data type, we can agree that they are two completely different things and are not comparable at all.

So what? might be your question. Look at the following code snippet and try to find out the bug.

As you might have noticed, when we try to remove the product from the shopping cart we accidentally end up passing the user id instead of the product id. Since this is a logical error, Swift has no idea and cannot warn us.

But what if we can ask Swift to help us out in the above situation? Follow along to learn how.

Here, we have created an Id wrapper object to hold our actual value. It also has a generic parameter PhantomType which not used inside the object. To help creating Id object easily, we have conformed to the ExpressiblebyIntegerliteral protocol.

We now create 2 data types to represent user and product Ids. Enum is the best candiate here since we don’t want to instantiate them.

We also update our existing models to use our Id type. It uses the previously created enums to substitute for the Phantom Type generic parameter that is required by the Id object.

Even though both of the above models internally use Int64 to store their ids they are now considered to be different data types by Swift since they use different generic parameters.

Let us now update our removeProduct function to use our new product id type.

Revisiting our bug from earlier, you can now observe that it is now impossible to accidently pass user id or any other id for that matter.

Swift will now complain and demand that you only pass a product id. We have now managed to convert what was orginally a run time bug to a compile time error by teaching Swift about our data types. Yaay! :grin:

--

--