0

I've got this Decodable struct:

struct MyDecodableTester: Decodable {
    let id: Int
    let name: String
    let snakeCase: String
    let mappedCodingKey: String

    enum CodingKeys: String, CodingKey {
        case id
        case name
        case snakeCase
        case mappedCodingKey = "code_key"
    }

    static func decode(from data: Data) -> Self? {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        do {
            return try decoder.decode(Self.self, from: data)
        } catch {
            print(">>> Error: \(error)")
        }

        return nil
    }
}

I tried calling the decode(from data:) function, using this JSON:

{
"id": 1,
"name": "name",
"snake_case": "snake_case",
"code_key": "code_key"
}

The problem is, it always throws this error:

keyNotFound(CodingKeys(stringValue: "code_key", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"code_key\", intValue: nil) (\"code_key\").", underlyingError: nil))

Even when I added the init(from coder:) function below, it always crashes because mappedCodingKey is nil.

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)

    id = try container.decodeIfPresent(Int.self,
                                           forKey: .id)!
    name = try container.decodeIfPresent(String.self, forKey: .name)!
    snakeCase = try container.decodeIfPresent(String.self,
                                             forKey: .snakeCase)!
    mappedCodingKey = try container.decodeIfPresent(String.self,
                                            forKey: .mappedCodingKey)!
}

I believe my JSON is already correct so I don't know why the error happened. Is there anything that I've missed here? How do I fix this?

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41

0 Answers0