Skip to content

Decoding a simple enum failed #114

@murad1981

Description

@murad1981

The basic usage of @Codable with enums is not explained in the docs, I couldn't find a simple example for basic type enums.

However, this led me to get stuck at this simple case:

@Codable
enum EnvironmentName: String {
    case test
    case staging
    //@CodedAs("OtherStaging")
    case otherStaging
}

@Codable
struct EnvironmentConfig {
    let name: EnvironmentName
    let backendHost: String
}

func parseConfig() {
    let jsonData = """
    {
        "name": "test",
        "backendHost": "myHost.com"
    }
    """.data(using: .utf8)!
        
        do {
            
            let decoder = JSONDecoder()
            let config = try decoder.decode(EnvironmentConfig.self, from: jsonData)
            print("The object is \(config)")
        } catch {
            print("Failed to decode JSON: \(error)")
        }
}

when calling the function parseConfig, the catch block is reached with this error:

Failed to decode JSON: typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "name", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a string instead.", underlyingError: nil))

I couldn't find a fix for this error.

And if I the value for the name key in the provided json is "OtherStaging", should I use @CodedAs("OtherStaging") beside the case name in the enum ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    invalidThis doesn't seem right

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions