Keep New Server Statuses From Breaking Your Codable Feed

Your shipping service adds an awaiting_customs status. The backend deploy succeeds. An older version of your app now fails to load the entire shipment list because its String enum only knows three values.

The parcel has reached customs. Your decoder has declared an international incident.

We can keep that shipment readable without pretending we understand its new state. The design has two parts: preserve unfamiliar strings when reading, and only offer actions whose meaning the app knows. Missing fields and incorrect JSON types still fail.

This is useful whenever the server and installed apps evolve on different schedules. It uses established Codable APIs, not a new decoding feature. The complete example below was checked with Xcode 27.2 RC and Swift 6.4.2; its iOS deployment target is 17.

Decide which part of the contract can grow

Imagine this response:

[
  {"id": 41, "status": "awaiting_pickup"},
  {"id": 42, "status": "awaiting_customs"},
  {"id": 43, "status": "delivered"}
]

A raw-value enum with only awaiting_pickup, in_transit, and delivered throws when it decodes the second status. Making the property optional doesn’t fix this: optional decoding handles a missing key or null, but a present, unrecognized string still fails to initialize that enum.

This is a recurring question, with existing answers. The Stack Overflow enum-decoding discussion includes unknown-value handling, and another question explores making unfamiliar values optional. Neither problem needs a blanket try? around every record.

For this API, we will allow the status vocabulary to grow. We will still require every record to contain an integer id and a string status. We won’t silently discard a record because another field is malformed.

If an unknown value determines how the rest of a payload must be interpreted—an encryption algorithm or a discriminant selecting an entirely different object schema, for example—rejecting it may be the correct policy. Only open the boundary you can actually support.

Store the wire value, then recognize what you know

Donny Wals’s custom Codable article explains both an associated other(String) case and a RawRepresentable wrapper. We’ll build on the wrapper approach, then add an explicit action boundary and tests for what must remain an error.

Put the Swift blocks in the same file, in order:

import Foundation

nonisolated struct ShipmentStatus: RawRepresentable, Codable, Hashable, Sendable {
    enum Known: String, Sendable {
        case awaitingPickup = "awaiting_pickup"
        case inTransit = "in_transit"
        case delivered
    }

    let rawValue: String

    init(rawValue: String) {
        self.rawValue = rawValue
    }

    init(_ known: Known) {
        self.rawValue = known.rawValue
    }

    var known: Known? {
        Known(rawValue: rawValue)
    }

    init(from decoder: any Decoder) throws {
        let container = try decoder.singleValueContainer()
        self.init(rawValue: try container.decode(String.self))
    }

    func encode(to encoder: any Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(rawValue)
    }
}

nonisolated struct Shipment: Codable, Equatable, Sendable {
    let id: Int
    let status: ShipmentStatus
}

ShipmentStatus holds one source of truth: the received string. known is a view of that value, not a second piece of stored state. When we eventually add awaitingCustoms to Known, the same stored string becomes recognizable.

The explicit single-value encoding and decoding keeps the JSON representation a string. We aren’t accidentally changing "delivered" into an object containing a rawValue key. RawRepresentable also supplies relevant Codable defaults for string raw values; writing the two methods here makes the wire contract visible and easy to test.

An associated-value enum is a valid alternative, provided its custom encoding preserves the API’s string representation. Synthesized encoding for associated-value enums uses a different, object-based shape. Adding case unknown(String) and relying on synthesis does not preserve this contract.

We don’t lowercase or trim the string. "DELIVERED", " delivered ", and even "" remain unfamiliar values under this example’s permissive string vocabulary. If the service contract forbids empty strings or imposes length limits, validate those requirements explicitly instead of quietly rewriting the value.

The nonisolated type declarations keep these data types independent of an app’s default actor isolation. Type-level nonisolated arrived in Swift 6.1; the underlying decoding technique predates it. The extension properties below are explicitly nonisolated too. Decoding is still synchronous, so these annotations alone don’t move work off the main actor. For substantial payloads, use an explicit processing owner such as the one in our large-feed article.

Show an honest fallback

The shipment can remain in the list with an understandable label:

extension ShipmentStatus {
    nonisolated var title: String {
        switch known {
        case .awaitingPickup: "Awaiting pickup"
        case .inTransit: "In transit"
        case .delivered: "Delivered"
        case nil: "Status unavailable in this version"
        }
    }
}

These are sample English labels; localize them in the app. The fallback doesn’t claim that the parcel is pending, cancelled, or delivered. It says that this client can’t describe the status. Keep ordinary record details visible, and offer an appropriate supported route—such as the service’s website—when the user needs more information.

Avoid displaying arbitrary server strings as polished UI copy or logging entire responses just to count unknown statuses. A bounded, privacy-conscious diagnostic can help the team notice new values without turning customer payloads into an analytics feed.

@unknown default is not a decoder setting. It helps handle future cases of nonfrozen enums in a switch; it doesn’t manufacture a value when a raw-value enum’s decoding has already failed.

Keep outgoing commands deliberately small

Being able to read a shipment doesn’t mean we should offer every action on it. Suppose our product only offers a cancellation request while a shipment awaits pickup:

nonisolated struct ShipmentActionRequest: Encodable, Equatable, Sendable {
    enum Action: String, Encodable, Sendable {
        case requestCancellation = "request_cancellation"
    }

    let shipmentID: Int
    let action: Action
}

extension Shipment {
    nonisolated var cancellationRequest: ShipmentActionRequest? {
        guard status.known == .awaitingPickup else { return nil }
        return ShipmentActionRequest(
            shipmentID: id,
            action: .requestCancellation
        )
    }
}

The UI can use cancellationRequest to decide whether to offer the action, then encode that request for the app’s existing networking layer. The resulting JSON contains only shipmentID and action. The request type has no arbitrary status-string field to echo back.

An unfamiliar status produces no cancellation request. So do the known in-transit and delivered states. This is a client presentation policy, not authorization: the server must validate the current state and permissions when it receives the request. A previously available action can become stale while the user reads the screen. Handle that rejection and refresh the record.

This separation also avoids a subtler failure. Decoding and re-encoding Shipment preserves its modeled status string, but it does not preserve unmodeled fields that the server added. Don’t use that partial model as a full-object replacement request. Prefer an API-defined command or a narrowly scoped update. If your endpoint requires a complete representation or a revision precondition, implement that contract explicitly.

Prove preservation without weakening validation

Here is a small executable example using the same mixed feed:

nonisolated func readShipmentExample() throws -> [Shipment] {
    let data = Data("""
    [
      {"id": 41, "status": "awaiting_pickup"},
      {"id": 42, "status": "awaiting_customs"},
      {"id": 43, "status": "delivered"}
    ]
    """.utf8)

    let shipments = try JSONDecoder().decode([Shipment].self, from: data)
    let saved = try JSONEncoder().encode(shipments)
    let restored = try JSONDecoder().decode([Shipment].self, from: saved)
    return restored
}

The result still contains IDs 41, 42, and 43 in order. Shipment 42 retains awaiting_customs, gets the fallback title, and offers no cancellation request. Shipment 41 offers the supported request. The round-trip preserves decoded string values, not the original JSON bytes, whitespace, escape spelling, or unmodeled fields.

Keep a failure matrix alongside the happy path:

Input or operationExpected result
Known and unfamiliar status strings in one arrayKeep every record in order
awaiting_customs and returned_to_senderKeep them distinct; don’t collapse both to one sentinel
Missing required statusThrow keyNotFound
"status": nullThrow valueNotFound
Numeric, Boolean, object, or array statusThrow typeMismatch
Missing or incorrectly typed idFail the record and the array decode
Encode an unfamiliar statusEmit the same decoded string value
Build a cancellation request from an unfamiliar statusReturn nil
Encode a supported cancellation requestEmit only the API’s command fields

The DecodingError cases let the caller distinguish those structural failures. A blanket try? would erase that distinction. If the product genuinely needs partial success, return rejected-record diagnostics deliberately; don’t make silent record loss the incidental effect of a fallback.

Download the complete sample and checks. The companion also checks the optional-enum failure, string wire shape, Unicode and escaped-string preservation, loss of unmodeled fields on re-encoding, and an old cache becoming recognizable after a vocabulary update.

Verification: the exact Swift blocks compile with Swift 6 warnings treated as errors for iOS 17 and macOS 14 deployment targets. The behavior checks run on macOS and an iOS 27 simulator, with both ordinary and MainActor default isolation. This example doesn’t implement networking, server authorization, persistent-cache recovery, or a complete shipment UI; those remain the consuming app’s responsibilities.

Keep unfamiliar information until you have a reason to reject it. Keep actions explicit until you have a reason to allow them. That gives an older app room to keep working without asking it to guess what the server meant.