I’m relatively new to Swift, and so I’m fortunate enough to come into it after it’s spent years maturing. Case in point: CodingKeys. From what I can gather from StackOverflow threads, later iterations of Swift made handling JSON much easier. After the addition of KeyDecodingStrategy with the built-in option to handle snake_case formatted keys, life got easier.

My particular issue was slightly different. Instead of my JSON data coming back with snake_case keys, it was coming back with Uppercased keys.

As someone who is largely self-taught and who has taken some online courses, handling this particular issue hadn’t been addressed in anything I’d come across. And when I would search for a way to handle this (I had previously left them uppercased to get successful network calls and upon reviewing my project remembered that I could certainly do better), a lot of the questions that popped up referred specifically to snake_case handling.

In short, here is the JSON I was looking to decode:

{
"API":"Cat Facts",
"Description":"Daily cat facts",
"Auth":"",
"HTTPS":true,
"Cors":"no",
"Link":"https://alexwohlbruck.github.io/cat-facts/",
"Category":"Animals"
}

and here is what my struct initially looked like:

struct Entry : Hashable, Codable {
    let API : String
    let Description : String
    let Auth : String?
    let HTTPS : Bool
    let Cors : String
    let Link : String
    let Category : String
}

After some investigating, it turns out that adding a simple enum, CodingKeys, like the following was all it took:

    private enum CodingKeys : String, CodingKey {
        case api = "API", description = "Description", auth = "Auth", https = "HTTPS", cors = "Cors", link = "Link", category = "Category"
    }

So when I added this to my existing struct, it looks like:

struct Entry : Hashable, Codable {
    let api : String
    let description : String
    let auth : String?
    let https : Bool
    let cors : String
    let link : String
    let category : String
    
    
    // MARK: custom coding key to handle uppercase keys from JSON data
    private enum CodingKeys : String, CodingKey {
        case api = "API", description = "Description", auth = "Auth", https = "HTTPS", cors = "Cors", link = "Link", category = "Category"
    }
}

In summary, it was a simple fix and no doubt something every iOS developer already knows, but introducing an enum to handle the keys allows you to specify the decoded keys to be anything you want.