Stringas we do above, we pass the encoding that we want the string to be decoded using – in this case
UTF8– by providing a reference to that type itself. It is very interesting. If we dive a little deeper, we can see that Swift's standard library defines the
UTF8type which we refer to above as a scissors enum within yet another namespace-like enum
Through the use of phantom types, the two above measured values cannot be mixed since the type of unit for which each value is encoded into that type of value. It prevents us from accidentally sending a length to a function that accepts an angle, and vice versa ̵1; just like how we prevented document formats from being merged before. […]
Using phantom types is an incredibly powerful technique that allows us to utilize type systems to validate different variants of a given value. Although the use of phantom types usually makes an API more complete, and comes with the general complexity of generic elements – when working with different formats and variants, it can reduce the dependency on runtime controls and allow the compiler to perform the controls instead.
Stay tuned by subscribing to the RSS feed for this post.