The Power of Swift Types
<!DOCTYPE html> The Power of Types

The Power of Types

Types matter.


Historically, popular programming languages provide interfaces like:

int distanceReachableWithFuel(int fuel_remaining_liters)

The function accepts one number and returns one number. It’s up to the programmer to always remember fuel is liters and the return value is — wait, what is the return value? The function doesn’t say. We’d have to read more documentation or read the function implementation to discover the return value meaning.

Then, an American shows up and writes:

int distance = distanceReachableWithFuel(15)

Maybe it was late and they were tired, maybe it was outsourced, or maybe they just didn’t consider the rest of the world doesn’t run on bespoke units from the 1700s. In any case, the American programmer gave a function taking liters a request for using 15 gallons.

It turns out, the type of distanceReachableWithFuel isn’t actually “accept a number and return a number,” but rather “Accept a fluid volume in Liters and return a linear distance in Kilometers.” In a more expressive language we could write:

Kilometers distanceReachableWithFuel(Liters fuel)

Now, distanceReachableWithFuel will fail to compile if the lazy programmer tries to call distanceReachableWithFuel(15) because the argument isn’t just an integer, it’s now an opaque type, and the forced type information makes very explicit the true real-world meaning of the values (under penalty of compiler error messages when faced with accidental misuse).

So, we end up with:

distance = distanceReachableWithFuel(Liters(15))

Now the programmer can use distance with absolute assurance they have a quantity of known units to pass through other parts of their system.


Situations where mismatched types go undetected and cause minor to major problems happen every day. Sometimes they escape local testing conditions and end up costing hundreds of millions of dollars in damage.

High profile, fully fully preventable, failures due to bad type enforcement include the $500+ million failure of Mars Climate Orbiter and even a simple fuel miscalculation resulting in a plane running out of fuel mid-flight.

Swift gives us an amazing type system built right in. It’s ready and waiting for you to build highly reliable and high performance applications right now.

If you’re in the mood for type theory-based entertainment, and why Java fails to have a real type system, check out Steve Yegge’s 2008 Rhinos and Tigers (video) too.

This Book

Throughout this book you’ll:

  • understand real-world situations where types matter
  • discover the Swift user defined container types
  • learn when to prefer one Swift container type over another
  • learn how to increase reliability of your programs with custom types
  • practice real world examples of defining custom types
  • practice converting custom Swift types to JSON