[swift-evolution] SE-0166: defaults for unmapped enums?

Marc Schlichte marc.schlichte at googlemail.com
Fri Apr 14 08:00:43 CDT 2017


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


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170414/0e49ae72/attachment.html>


More information about the swift-evolution mailing list