Exploring RawRepresentable and Enums in Swift

Enums for Raw types

Steven Curtis
3 min readMar 22, 2023
Photo by Parker Johnson on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

RawRepresentable is a protocol from the Swift standard library. We might be aware of this in that conformance is autosynthesized — but are we able to dive deeper? This article is designed to help us do just that.

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)
  • Know about Segues in iOS applications (guide HERE)
  • Understand the use or Enums in Swift (guide HERE)

Terminology

Character: A character, usually associated with a letter of the alphabet

Enum: A type consisting of a set of named values, called members

RawRepresentable: A type that can be converted to and from an associated raw value

The Motivation

When using enum types as in the Counts case below, the Swift compiler automatically adds RawRepresentable conformance

enum Counts: Int {
case one
case two
}

The first case has an automatic value of 0, for clarity.

--

--