Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 146 ยท Structures, Classes and Enums

Enumerations

Learn Swift enumerations - cases, exhaustive switch, raw values, associated values, CaseIterable, methods, mutating, static members and how enums make invalid states impossible.

An enumeration, or enum, is a type with a fixed list of possibilities. A traffic light is red, yellow or green. A file is open, closed or failed. A network request is idle, loading, loaded or broken. You could model each of these with strings or integers, but then nothing stops a typo ("gren") or a nonsense number (7). An enum gives the possibilities names, makes the compiler check them, and lets the compiler tell you when you forgot to handle one.

In many languages an enum is just a list of named integers. Swift enums are much more powerful: a case can carry data of its own, an enum can have methods and computed properties, and it can conform to protocols. Swift's own Optional and Result types are ordinary enums. This lesson covers all the pieces: plain cases, switch, raw values, associated values, iterating over all cases, and adding behavior. The next lesson, Indirect Enums and Recursive Types, shows how enums can contain themselves.

Declaring an enum

An enum lists its cases with the case keyword. By convention the type name is UpperCamelCase and each case is lowerCamelCase:

Swift A first enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You can also put several cases on one line (case north, south, east, west). Once a variable has the type Direction, you can write .east without the type name, because the compiler already knows which enum you mean. That leading-dot form is used everywhere in Swift code.

Notice two things. First, print shows the case name, which is handy when debugging. Second, == works without any extra code: an enum whose cases carry no data is automatically Equatable and Hashable, so you can compare values and use them as dictionary keys or set members.

Cases are not integers. Direction.north is not 0, you cannot add two of them, and nothing converts silently. That is the point: the type has exactly four possible values, and the compiler knows it.

Matching with switch

The natural partner of an enum is switch. Swift requires a switch to be exhaustive: every case must be handled, or you must write a default.

Swift Switching over an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The function has no default, and that is deliberate. Because every case is listed, the compiler is satisfied, and it will complain later if someone adds a fifth case. The last part of the example uses switch as an expression (Swift 5.9): each branch produces a value, and the whole switch becomes the value of isVertical.

Let's see what the compiler says when you forget a case.

Swift A switch that misses a case (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with error: switch must be exhaustive and adds note: add missing case: '.yellow'. That error is a feature. When your enum grows, every switch that has no default becomes a to-do list the compiler writes for you.

Be careful with default. It silences the exhaustiveness check, so a new case quietly falls into the default branch with no warning. Prefer listing every case when the enum is yours and the behavior should be decided case by case. Use default when you really mean "everything else".

Enums from other libraries

If an enum comes from a library that might add cases later, Swift offers the @unknown default label. It behaves like default, but the compiler still warns you when a case is newly added and not handled. You will meet it mostly with Apple frameworks and library enums marked as non-frozen; for your own enums a plain exhaustive switch is better.

Raw values

Sometimes each case should correspond to a fixed value, such as a code stored in a file or sent over the network. Declare a raw type after the enum name, and give each case a raw value:

Swift Raw values and init(rawValue:)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Four things to take from this program:

  • The raw type can be Int, String, Character, Double and the other literal types. Each raw value must be unique within the enum.
  • rawValue converts a case to its raw value.
  • init?(rawValue:) goes the other way. It is failable: it returns an optional, because a number like 301 matches no case. You must handle nil, usually with if let or guard let (see Optionals).
  • Raw values fill themselves in. Integer raw values count up from the previous case (venus is 2, earth is 3, and so on), starting at 0 if you write none. A String raw value defaults to the case name.

Raw values are how an enum talks to the outside world. A Codable enum with a String raw type, for example, reads and writes JSON strings with no further code (see Codable).

An enum has either a raw value or associated values on its cases, never both for the same case. Raw values are fixed at compile time and identical for every instance of a case. Associated values are filled in each time you create a value.

Associated values

This is the feature that makes Swift enums special. A case can carry data of its own, and different cases can carry different data:

Swift Cases that carry data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Payment.cash holds a Double, .card holds two strings, .voucher holds one string, and .free holds nothing. A value of type Payment is always exactly one of these, together with its data. The switch pulls the data out by binding it to names with let. You can ignore a piece with _, and you can write case let .cash(amount) instead of case .cash(let amount), which is the same thing.

Why is this better than a struct with optional fields? Compare:

Swift
// Read-only example: the weaker design
struct PaymentStruct {
    var kind: String
    var amount: Double?
    var cardNumber: String?
    var voucherCode: String?
}

With the struct, nothing prevents a kind of "cash" with a card number, or "card" with no number at all. The enum makes those states impossible to write. This idea is often summed up as make illegal states unrepresentable, and it removes whole categories of bugs.

Pattern matching with where and conditions

Because switch matches on structure, you can add conditions to a case with where, or match a specific payload with a pattern:

Swift where clauses on associated values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Note case .circle: on its own: when you do not need the payload you may leave the parentheses off entirely. The last lines show if case, a one-case pattern match, which is shorter than a full switch when you care about a single case. Pattern Matching goes much deeper.

Iterating over all cases: CaseIterable

Often you want a list of every case, for a menu or for testing. Add the CaseIterable protocol, and the compiler writes a static allCases property for you:

Swift CaseIterable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

allCases is an array of the cases in declaration order. This only works automatically for enums without associated values, because an enum such as Payment has infinitely many possible values (every possible amount). If you try, the compiler refuses to synthesize the conformance.

Methods, computed properties and mutating

An enum is a full type. It can have computed properties, methods, initializers and static members, just like a struct. Stored properties are the one exception: an enum cannot have them, because the only stored data is the current case and its payload.

Swift Behavior inside an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

next and seconds are computed properties that switch on self. advance() is mutating and assigns a whole new case to self, something only enums and structs can do (a mutating method on a value type can replace the entire value). cycleLength is a type property that uses the automatic allCases. Because behavior lives next to the data, the rest of your program just writes light.advance().

Custom initializers

An initializer for an enum must assign a case to self:

Swift An initializer that picks a case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

This pattern (turn a raw measurement into a small set of categories) is very common. Here the switch over a Double uses ranges, which you saw in switch.

Comparing and sorting enums

Plain enums are Equatable automatically. For ordering, add Comparable. If the enum has no raw type and no associated values (or only comparable ones), Swift synthesizes < from the declaration order of the cases:

Swift Comparable enums

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Because order comes from the written order, rearranging the cases changes the sorting, which is a quiet way to break a program. For enums with a raw type, compare the raw values instead if you want an order you control explicitly.

Optional is an enum

You have already used an enum without noticing. Optional<Wrapped> is declared in the standard library roughly like this:

Swift
// Read-only example: the idea behind Optional
enum Optional<Wrapped> {
    case none
    case some(Wrapped)
}

nil is simply .none, and a value is .some(value). The if let and ? syntax are shortcuts for matching those two cases. You can prove it:

Swift Optional is just an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Knowing this makes pattern matching, Result, and error handling easier to understand: they are all enums with payloads.

Choosing between an enum and other tools

Use an enum when a value is one of a fixed set of alternatives known at compile time: states, kinds, commands, results, options. Use a struct for a bundle of values that all exist together, and a class for shared identity. Avoid enums for sets that grow at runtime (use a struct with a String or a database id), and avoid huge enums with dozens of payload shapes, which are better split into smaller types or modeled with protocols.

One more design hint: a switch that appears in many places for the same enum is a sign that behavior should move into the enum as a method or property, as Light did above.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the compiler do when a switch over an enum leaves out a case and has no default?

    Swift requires a switch to cover every possible value. A missing case is a compile-time error, which is also a helpful reminder when you add new cases later.
  2. 2. What type does HTTPStatus(rawValue: 301) return when no case has that raw value?

    init?(rawValue:) is failable. It returns an optional enum value, and nil means no case matches.
  3. 3. Which enum can use CaseIterable and get allCases automatically?

    Automatic allCases works for enums whose cases carry no associated values, because only then is the list of values finite.
  4. 4. Why is an enum with associated values often a better model than a struct with several optional fields?

    Each case carries exactly the data it needs, so states like a cash payment with a card number cannot exist.
  5. 5. Can an enum have stored properties?

    An enum's stored data is its current case and that case's associated values. It can still have computed properties, methods and static properties.

Summary

  • An enum is a type with a fixed set of cases; Direction.north or just .north when the type is known.
  • A switch over an enum must be exhaustive, so the compiler tells you about unhandled cases; use default sparingly.
  • Raw values (enum Mode: String) give each case a fixed value; init?(rawValue:) returns an optional.
  • Associated values let each case carry its own data, which makes illegal states unrepresentable.
  • CaseIterable provides allCases for enums without associated values.
  • Enums can have computed properties, methods, mutating methods, initializers and static members, but no stored properties.
  • Cases without payloads are Equatable and Hashable automatically; add Comparable to order by declaration.
  • Optional and Result are ordinary enums.

Next: Indirect Enums and Recursive Types