skip to content

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%

answer

  1. failable, so the result is optional
  2. exact match on raw values
  3. case name text for String
  4. previous plus one for Int
  5. renaming a case changes the wire value

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.

solid answer

~50 s

The initializer is failable, so `PaymentMethod(rawValue: "crypto")` has type `PaymentMethod?` and is `nil` for any string that no case declares: matching is exact equality on the raw value, case-sensitive, and never on the case name when an explicit raw value differs. Nothing traps; the caller decides, typically with a non-failable wrapper such as `PaymentMethod(rawValue: value) ?? .unsupported`, or by logging and dropping the item. Implicit raw values come from the declaration: for `String`, the text of the case name; for `Int`, 0 for the first case and the previous value plus one after that, so `case low = 1, normal` makes `normal` 2. Because an implicit `String` raw value is the case name, renaming a case in a refactor silently changes what goes over the wire, so values shared with an API should be written out explicitly.

code

swift · 18 lines
swift
enum PaymentMethod: String, CaseIterable {
    case card                              // raw value "card" (implicit)
    case applePay = "apple_pay"            // explicit: the API's spelling
    case bankTransfer = "bank_transfer"
    case unsupported

    // Non-failable entry point for values that come off the wire.
    init(apiValue: String) {
        self = PaymentMethod(rawValue: apiValue) ?? .unsupported
    }
}

let exact = PaymentMethod(rawValue: "apple_pay")   // Optional(.applePay)
let caseName = PaymentMethod(rawValue: "applePay") // nil: matches raw values, not case names
let unknown = PaymentMethod(apiValue: "crypto")    // .unsupported

print(exact == .applePay, caseName == nil, unknown)
// true true unsupported

go deeper

for a junior

Remember that init?(rawValue:) returns an optional and is nil for an unknown value, and that String cases default to their own names as raw values.

for a middle

Walk through the synthesized RawRepresentable members, exact case-sensitive matching, and how implicit Int values continue after an explicit one.

for a senior

Treat raw values as a wire contract: explicit values for anything persisted or sent, a deliberate policy for unknown values, and a test that pins each raw value.

for a principal

Decide where unknown values are absorbed, at the network boundary or deep in the feature, and how a new backend value reaches users before the app updates.

## The failable initializer every raw-value enum gets Declaring a **raw type**, as in `enum PaymentMethod: String`, makes the enum conform to the standard library's `RawRepresentable` protocol. The compiler synthesizes two members: - `var rawValue: String`, the constant attached to each case; - `init?(rawValue: String)`, a **failable initializer** whose result is `PaymentMethod?`. The standard library documents the contract on `RawRepresentable`: if there is no value of the type that corresponds to the given raw value, the initializer returns `nil`. So an undocumented value such as `"crypto"` does not crash, does not fall back to the first case and does not throw. It produces `nil`, and the type system forces the caller to decide what that means. ## How the match works The synthesized initializer compares the argument against each case's raw value with `==` on the raw type: - the comparison is **exact** and therefore case-sensitive for `String`: `"APPLE_PAY"` does not match `"apple_pay"`; - it compares **raw values, not case names**: with `case applePay = "apple_pay"`, the string `"applePay"` returns `nil`; - raw values are unique by rule ("raw value for enum case is not unique" otherwise), so at most one case can match. ## Implicit raw values You do not have to write a raw value for every case. The compiler fills in the ones you leave out: | Raw type | Implicit value of an unassigned case | |---|---| | `String` | the text of the case name: `case card` is `"card"` | | `Int` and other integer types | `0` for the first case, then the previous raw value plus one | | `Double` and `Float` | the same counting, since they accept integer literals: `0.0`, `1.0`, … | | `Character` | none: every case needs an explicit value | Two details trip people up. After an explicit value the count continues from it, so `enum Priority: Int { case low = 1, normal, high, urgent = 10, critical }` gives `high` the value 3 and `critical` 11. And when the preceding raw value is not an integer, as after `case max = 9.5` in a `Double` enum, the next case must be written out, or the compiler reports "enum case must declare a raw value when the preceding raw value is not an integer". For `Character` the error is "enum cases require explicit raw values when the raw type is not expressible by integer or string literal". ## Handling values you do not recognise A payment method enum whose raw values travel to and from an API meets new values the day the backend ships one. The common Swift patterns are: 1. Keep the failable initializer and handle `nil` at the boundary: skip the row, log it, or show a generic option. 2. Add a catch-all case such as `.unsupported` and a non-failable initializer, `init(apiValue:)`, that returns `PaymentMethod(rawValue: apiValue) ?? .unsupported`. 3. When the unknown string itself must be kept, drop the raw type: a raw-value enum cannot have a payload case like `case unknown(String)`, so the enum implements `init?(rawValue:)` and `rawValue` by hand instead. Option 2 is convenient but lossy. Once `"crypto"` has become `.unsupported`, its `rawValue` is `"unsupported"`, so a model that writes the value back to the server or to disk replaces the real value with the placeholder. Use the catch-all for display decisions, and keep the original string wherever the value is round-tripped. How a decoder uses the raw value when the enum also adopts `Codable` is a separate subject, covered with Codable. ## The refactoring hazard Implicit `String` raw values couple an external contract to an internal name. Renaming `case bankTransfer` to `case transfer` compiles cleanly and changes the raw value from `"bankTransfer"` to `"transfer"`, so values already stored on disk or sent by the server stop matching and start returning `nil`. Implicit `Int` raw values have the same hazard with order: inserting a case in the middle renumbers every case after it. The defensive habits: - write explicit raw values for every enum whose raw value leaves the process; - never insert into the middle of an implicitly numbered enum that is persisted; - add a test that pins each case to its expected raw value, so a rename fails a test instead of production.

  • What raw values does `enum Priority: Int { case low = 1, normal, high, urgent = 10, critical }` give `high` and `critical`?
    `high` is 3 and `critical` is 11. Each unassigned case takes the previous raw value plus one, and an explicit value such as `urgent = 10` restarts the count from there. `Priority(rawValue: 4)` is `nil`, because no case has 4.
  • Why not add `case unknown(String)` to keep the unrecognised value?
    A raw-type enum cannot have cases with arguments, so the compiler rejects it. To keep the string, drop the raw type and implement `RawRepresentable` yourself, with `init?(rawValue:)` mapping known strings to cases and anything else to `.unknown(value)`, and `rawValue` returning the stored string for that case.

  • `init?(rawValue:)` matches the case name even when an explicit raw value differs.
  • An unknown raw value makes `init?(rawValue:)` trap at run time.
  • Raw-value matching on String ignores letter case.
  • Implicit Int raw values start at 1.
  • Renaming a case can never change stored or transmitted data.