Phantom Types in Swift To Catch Errors At Compile Time

Here’s a good setup on where a phantom type in Swift may be helpful:

“Sometimes, we want to have additional safety when dealing with important types in our application. For example, suppose your application revolves around file handles, and you want to be sure that you never try to perform any write operations on a file handle that’s open for reading.”

The code example shows using phantom types to create wrappers around NSFileHandle’s initializers. With this approach permissions can be tracked such that calling a function to read a file, that is open for writing, will generate a compile time error.

I’m all for catching as many errors as possible during a build versus runtime.