In Swift, what is the difference between an enum's raw values and its associated values, and can one enum declare both?
answer
- fixed at declaration vs chosen per value
- one shared type for every case
- payload types can differ per case
- RawRepresentable gives rawValue
- raw type rules out cases with arguments
basics
~20 sRaw 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 sRaw 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 linesenum 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
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.
Explain that a raw type makes the enum RawRepresentable, with rawValue and a failable init?(rawValue:), and why that synthesis rules out payload cases.
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.
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.