Phantom types

Swift language Senior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

You keep passing a user ID where an order ID is expected. Both are UUIDs. Which prevents it at compile time?

Options
Hint 1 of 1

Does a typealias create a new type?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A struct ID<Tag>: Hashable { let raw: UUID } with ID<User> and ID<Order>

Correct. Different tags make different types.

Why not the others?
  • B typealias UserID = UUID and typealias OrderID = UUID. Typealiases are just new names; the compiler treats them as the same type.
  • C Naming parameters clearly. It helps readers, but nothing stops a mix-up.
  • D Subclass UUID. UUID is a struct; you can't subclass it.

30-second answer

A phantom type is a generic parameter that is never stored, used only to give values different types at compile time. ID<User> and ID<Order> share an implementation but can't be mixed up. This catches bugs like passing an order ID where a user ID is expected, at no runtime cost.

Practise saying it · 30 s. No recording, just a timer

Explain phantom types.

Say your answer out loud, then check which of these points you covered:

  • Unused generic tag
  • Compile-time distinction
  • IDs, units, states

Deep dive

Use empty enums as tags: enum UserTag {}.

Works well for IDs, units (Distance<Meters>) and state machines (Request<Unvalidated>).

Conditional conformances can give each tag different methods.

Keep it simple; too many phantom types make APIs hard to read.

Common mistakes

  • Using typealiases and expecting type safety.
  • Overusing phantom types for everything.

Senior take & follow-ups

Seniors give a concrete bug that phantom types prevent.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why use an empty enum as the tag?

    Show hint

    It can't be instantiated, so it is only a type.

  2. How do phantom types model states?

    Show hint

    Methods that exist only for certain tags, via constrained extensions.

Suggest a fix if something here is wrong or out of date.