skip to content

Enumerations and Switch

Enums with associated values model state, and switch matches them exhaustively with patterns. Interviewers like both because they replace a pile of loosely related optional properties.

on this pageshow

explore

questions

10

In Swift, what is the difference between an enum's raw values and its associated values, and can one enum declare both?

level: juniorimportance: must knowfreq 72%

answer

  1. fixed at declaration vs chosen per value
  2. one shared type for every case
  3. payload types can differ per case
  4. RawRepresentable gives rawValue
  5. raw type rules out cases with arguments

basics

~20 s

Raw values are per-case constants of one shared type, fixed in the declaration; associated values are payloads supplied each time a value is created, typed per case. A Swift enum with a raw type cannot give any case associated values.

solid answer

~40 s

Raw values are compile-time constants: with `enum PaymentMethod: String` every case gets one value of that type, written out or implicit, and a given case always has the same `rawValue`. The enum then conforms to `RawRepresentable`, which gives it `rawValue` and the failable `init?(rawValue:)`. Associated values are a payload: `case loaded([Article])` declares what the case carries, each value carries its own data, and different cases can carry different types. The two forms do not mix in one declaration: a raw type plus a case with arguments fails with "enum with raw type cannot have cases with arguments". When you need both, keep the payload enum and add a computed property that maps each case to a string, or implement `RawRepresentable` by hand.

code

swift · 21 lines
swift
enum PaymentMethod: String {
    case card
    case applePay = "apple_pay"
    case bankTransfer = "bank_transfer"
}

enum LoadState {
    case idle
    case loading
    case loaded([String])
    case failed(message: String)
}

let method = PaymentMethod.applePay
print(method.rawValue)                 // apple_pay
print(PaymentMethod.card.rawValue)     // card (implicit)

let first = LoadState.loaded(["Enums", "Structs"])
let second = LoadState.loaded([])      // same case, different payload
let failure = LoadState.failed(message: "Offline")
print(first, second, failure)

go deeper

for a junior

Recall the two timings: a raw value is fixed when the enum is written, an associated value is chosen when a value is created. Know that rawValue exists only when a raw type is declared.

for a middle

Explain that a raw type makes the enum RawRepresentable, with rawValue and a failable init?(rawValue:), and why that synthesis rules out payload cases.

for a senior

Show which one you reach for: raw values for identifiers that cross a process boundary, payloads for state, and a computed property or a hand-written RawRepresentable when a payload enum needs a stable string.

for a principal

Frame the choice as a contract question: a raw value is a promise about stored and transmitted data, a payload is a promise about which data exists in which state. Decide which promise each enum in a codebase makes.

## Two ways to attach data to a case A Swift **enumeration** declares a closed set of **cases**. A plain case such as `case idle` carries no data at all, and unlike C, Swift does not give it a hidden integer. When a case needs data, Swift offers two different mechanisms, and interviewers ask about them together because candidates often blur them: - a **raw value** is a constant attached to a case when the enum is declared; - an **associated value** is a payload attached to a case each time a value of that case is created. ## Raw values: one constant per case You opt in by writing a **raw type** after the enum name, as in `enum PaymentMethod: String`. Then: - every case has exactly one raw value of that type, written as `case applePay = "apple_pay"` or assigned implicitly (the case name for `String`, counting up from `0` for `Int`); - each raw value must be unique, or the compiler reports "raw value for enum case is not unique"; - the raw type must be expressible by a string, integer or floating-point literal, so `String`, `Character`, the integer types and the floating-point types qualify; - the enum conforms to `RawRepresentable` automatically, which gives it a `rawValue` property and a failable initializer `init?(rawValue:)` that returns `nil` when no case has that raw value. The important property is that the raw value belongs to the **case**, not to the instance: `PaymentMethod.applePay.rawValue` is `"apple_pay"` everywhere in the program, forever. That makes raw values a good fit for identifiers that travel to an API, a database column or `UserDefaults`. ## Associated values: a payload per value An associated value is declared as a tuple of types after the case name: `case loaded([String])`, `case failed(message: String)`. Then: - each case can declare its own payload types, with optional labels, and cases without payloads can sit beside them; - the payload is chosen when the value is created, so `.loaded(["Enums"])` and `.loaded([])` are the same case holding different data; - a payload case can be used like a function: `LoadState.loaded` has the type `([String]) -> LoadState`, so it can be passed to `map`; - reading the payload back means matching the case, with `switch` or `if case let`, which the Swift lesson on case patterns covers. This is what makes Swift enums a modelling tool rather than a list of named constants: a screen's load state can be `idle`, `loading`, `loaded` with its articles or `failed` with its message, and the articles exist only inside the case where they are valid. ## Side by side | | Raw value | Associated value | |---|---|---| | Chosen | once, in the declaration | every time a value is created | | Type | one raw type for all cases | any types, different per case | | Same for every value of a case | yes | no | | Access | `rawValue`, `init?(rawValue:)` | pattern matching on the case | | Protocol | `RawRepresentable`, synthesized | none implied | ## Why they do not mix, and what to do instead The synthesized `init?(rawValue:)` must build a case from nothing but the raw value, and a case with a payload cannot be built that way. So the compiler rejects the combination with two errors: "enum with raw type cannot have cases with arguments" on the case, and a second one saying the enum "declares raw type 'String', but does not conform to RawRepresentable and conformance could not be synthesized". When you need a stable string for a payload enum, you have two honest options: 1. Drop the raw type and add a computed property, such as `var analyticsName: String`, that switches over `self` and returns a string per case. 2. Conform to `RawRepresentable` by hand: declare `init?(rawValue:)` and `var rawValue` yourself and decide how a payload maps to and from the raw value. One related difference: an enum without associated values is `Equatable` and `Hashable` automatically, while a payload enum gets those conformances only when it declares them and every payload type supports them. The lesson on equality and hashing covers the rules. ## What interviewers listen for A strong answer says **when** each value is chosen (declaration vs creation), says that raw values share one type while payload types vary per case, names `RawRepresentable` and the failable initializer, and knows the compiler refuses a raw type on an enum with payload cases. A weak answer treats raw values as hidden integers every enum has, or tries to put a payload on a `String`-backed enum.

  • Why does `PaymentMethod.card == .applePay` compile while the same comparison on a payload enum fails?
    An enum without associated values is `Equatable` and `Hashable` automatically. A payload enum has to declare `Equatable`; the compiler then synthesizes `==` only when every payload type is `Equatable`. Without that declaration, `==` on it fails with "referencing operator function '==' on 'Equatable' requires that 'LoadState' conform to 'Equatable'".
  • Can associated values carry labels and default values?
    Yes. `case failed(message: String, retryable: Bool = true)` is legal, and `.failed(message: "Offline")` then fills `retryable` with `true`. Labels make construction read clearly and can be used when matching, but the payload is still chosen per value, not per case.
  • What is `LoadState.loaded` without parentheses?
    A function. A payload case can be referenced as a value of type `([String]) -> LoadState`, so `[["a"], ["b"]].map(LoadState.loaded)` builds an array of loaded states. A case without a payload, such as `LoadState.idle`, is just a value of the enum.

  • Every Swift enum case has a hidden integer value starting at zero.
  • A raw value can be set differently each time the case is created.
  • All associated values in an enum must share one type, like raw values.
  • You can add `: String` to an enum whose cases carry payloads.
  • Every enum has `rawValue`, whether or not it declares a raw type.
open as a page

In Swift, how does a switch match tuple and range patterns, such as a deep link's (host, path) pair or an HTTP status code?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A Swift switch matches a tuple element by element, with _ ignoring a position, and a range by containment. The first matching case in source order wins; a switch over Int or String still needs a default case.

open as a page

In Swift, what does a String-backed enum's `init?(rawValue:)` return for a value the API never documented, and how are implicit raw values chosen?

level: middleimportance: must knowfreq 62%

basics

~10 s

init?(rawValue:) returns nil when no case has that exact, case-sensitive raw value. Implicit raw values are the case name for String and the previous value plus one, from 0, for integer raw types.

open as a page

In Swift, how do you bind an enum case's associated values in a switch, and when do you use if case, guard case or for case instead?

level: middleimportance: must knowfreq 75%

basics

~20 s

Bind payload values with let or var inside the case pattern, as in case .failure(let status, _), optionally filtered by where. Use if case or guard case to test one case without a switch, and for case to loop over matches.

open as a page

When does Swift synthesize `CaseIterable` for an enum, and what do you do for an enum whose cases carry associated values?

level: middleimportance: should knowfreq 45%

basics

~20 s

Swift synthesizes allCases when an enum declares CaseIterable, has no associated values and no @available attributes on its cases, and the conformance is in the enum's own file. Otherwise you write static var allCases yourself.

open as a page

In a Swift switch over a value of type Any, what do the case is T and case let x as T patterns do, and why does case order matter?

level: middleimportance: should knowfreq 40%

basics

~20 s

case is T matches when the value's runtime type is T or a subclass; case let x as T matches the same values and binds x as T. The first match wins, so a superclass case placed first hides its subclasses.

open as a page

Why does Swift reject a recursive enum for an expression tree with "recursive enum 'Expr' is not marked 'indirect'", and what does `indirect` change?

level: seniorimportance: should knowfreq 40%

basics

~20 s

An enum is a value type with a fixed size, and a case that stores another Expr inline would make that size infinite. indirect makes the compiler store that case's payload in a separately allocated box and keep only a reference inline.

open as a page

In Swift, why does a switch over an SDK enum such as URLSessionTask.State need @unknown default, and how does Swift 6 language mode change the diagnostic?

level: seniorimportance: should knowfreq 50%

basics

~20 s

A nonfrozen enum (from C or Objective-C, the standard library or a library-evolution module) can gain cases after you ship. @unknown default handles those yet still flags skipped known cases; omitting it warns in Swift 5 mode, errors in Swift 6 mode.

open as a page

Your Swift screen model has `isLoading`, `articles: [Article]?` and `error: Error?`; when do you replace it with an enum with associated values, and what does that cost?

level: principalimportance: should knowfreq 50%

basics

~20 s

Replace the flags when the states are mutually exclusive: an enum with payloads makes contradictory combinations unrepresentable. The costs are no stored properties on enums, payload types that must be Equatable for synthesis, and a source break whenever a case is added.

open as a page

How does a Swift switch use the ~= operator for expression patterns, and what changes when you overload ~= for your own matcher type?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Swift evaluates an expression pattern as pattern ~= value: the standard library's ~= uses == for Equatable values and contains for ranges. Overloading ~= for a matcher type lets custom values sit in case labels, but such a switch always needs default.

open as a page