SE-0166: defaults for unmapped enums?


(Marc Schlichte) #1

We sometimes encounter the situation that a server will add over time new values to existing `enums`.

e.g. in the `enum Animal` example `cat` gets added.

To not break existing clients, we often use something like this:

    enum Animal: Int, Codable {
        case unknown = 0
        case chicken = 1, dog, turkey, cow
    }

and all cases which are unknown (like a new `cat` case) will map to `unknown` instead.

I could probably do this by manually implementing `init(from:)`:
  
    public init(from decoder: Decoder) throws {
        // Decodes as a single value; no keys.
        let intValue = try decoder.singleValueContainer().decode(Int.self)
        if let value = Self(rawValue: intValue) {
            self = value
        } else {
            self = .unknown
        }
    }

But maybe there is a better way envisioned by the authors of SE-0166?

Cheers
Marc