how to use decodable with enum?

Asked on 08/22/2024

1 search

To use Decodable with an enum in Swift, you can leverage Swift's powerful enum capabilities, which allow you to represent a choice between different cases, potentially with associated values. Here's a general approach to making an enum conform to Decodable:

  1. Define the Enum: Create your enum with cases. If needed, include associated values for each case.

  2. Conform to Decodable: Implement the Decodable protocol for your enum. This typically involves writing a custom initializer that decodes the enum from a Decoder.

  3. Use a Switch Statement: Within the initializer, use a switch statement to handle different cases based on the data being decoded.

Here's a simple example:

enum MyEnum: Decodable {
    case on
    case off
    case level(Int)
    case color(hue: Int, saturation: Int)

    enum CodingKeys: String, CodingKey {
        case type
        case value
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let type = try container.decode(String.self, forKey: .type)

        switch type {
        case "on":
            self = .on
        case "off":
            self = .off
        case "level":
            let value = try container.decode(Int.self, forKey: .value)
            self = .level(value)
        case "color":
            let hue = try container.decode(Int.self, forKey: .value)
            let saturation = try container.decode(Int.self, forKey: .value)
            self = .color(hue: hue, saturation: saturation)
        default:
            throw DecodingError.dataCorruptedError(forKey: .type, in: container, debugDescription: "Invalid type")
        }
    }
}

This example demonstrates how to decode an enum with different cases, some of which have associated values. The use of a switch statement allows you to handle each case appropriately, leveraging Swift's pattern matching capabilities.

For more detailed information on using enums in Swift, you might find the session Go small with Embedded Swift helpful, as it discusses the power and expressiveness of Swift enums.