Monday, August 5, 2019

Phantom Types in Swift

John Sundell:

When converting Data into a String, like we do above, we pass the encoding that we want the string to be decoded using — in this case UTF8 — by passing a reference to that type itself. That’s really interesting. If we dive a bit deeper, we can then see that the Swift standard library defines the UTF8 type that we refer to above as a case-less enum within yet another namespace-like enum called Unicode[…]


Through the use of phantom types, the above two measurement values can’t be mixed, since what kind of unit that each value is for is encoded into that value’s type. That prevents us from accidentally passing a length to a function that accepts an angle, and vice versa — just like how we prevented document formats from being mixed up before.


Using phantom types is an incredibly powerful technique that can let us leverage the type system in order to validate different variants of a given value. While using phantom types usually makes an API more verbose, and does come with the added complexity of generics — when dealing with different formats and variants, it can let us reduce our reliance on run-time checks, and let the compiler perform those checks instead.


Comments RSS · Twitter

Leave a Comment