قالب وردپرس درنا توس
Home / Apple / Michael Tsai – Blog – Phantom types in fast

Michael Tsai – Blog – Phantom types in fast



John Sundell:

When converting Data to a String as 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 UTF8 type which we refer to above as a scissors enum within yet another namespace-like enum Unicode […] […]

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.

Previous:

Cocoa iOS iOS 12 Mac macOS 10.14 Mojave Programming Swift Programming Language

Stay tuned by subscribing to the RSS feed for this post.


Source link