Handling Unknown Enum Cases in Swift

Using an Unknown Case with Codable

Steven Curtis
4 min readNov 17, 2024
Photo by Arno Senoner on Unsplash

In swift enum can be used to represent a fixed set of options, perhaps to manage state or represent user choices.

Yet when we use enum to work with network data we can experience issues — what happens if the data source adds a new case that your enum doesn’t recognize? In the worse case we could have an app that will crash which is completely unacceptable.

This article is about a solution to that problem. We can introduce an unknown case into the enum and handle the result gracefully.

In this article, we’ll explore how to set up an unknown case in a Codable enum, why it’s useful, and how it works within an initializer.

Introducing The Problem

We might use an enum to represent the status of a user account that comes from a network response.

enum Status: String, Codable {
case active
case inactive
case pending
}

Each case reflects a possible state of a user account, and as long as the Status is not changed there is no issue with this.

However, we might experience an issue if we need to introduce a new status. Even if we update the app we cannot guarantee that the user will update and avoid a crash.

--

--

Responses (1)