Skip to content

Instantly share code, notes, and snippets.

@christianselig
Last active October 27, 2022 18:55
Show Gist options
  • Save christianselig/92b75f6bc94a76b8ab2a45b0115b39c2 to your computer and use it in GitHub Desktop.
Save christianselig/92b75f6bc94a76b8ab2a45b0115b39c2 to your computer and use it in GitHub Desktop.

If I have a JSON Codable object in Swift that looks like:

struct IceCreamStore: Codable {
    let iceCreams: [IceCream: Int]
}

enum IceCream: String, Codable {
    case chocolate, vanilla
}

And I accidentally encoded a strawberry field from a new version of the app, so that the dictionary now has a strawberry field in it, that this older version of the app doesn't know how to deal with (and thus can't decode it and errors), is there a way to conditionally decode it and just ignore that strawberry value? I tried using CodingKeys and decoding it as a [String: IceCreamInfo] instead manually, but no dice, still won't decode as that. I don't want to add strawberry manually as a value for a number of reasons but just consider those academic.

It's basically trying to ingest:

{
    "chocolate": 8,
    "vanilla": 4,
    "strawberry": 3
}

When it doesn't know how to deal with strawberry, and I want to just have it ignore the strawberry.

Like, in my head I want to do:

let container = try decoder.container(keyedBy: CodingKeys.self)
let manualDictionary = try container.decode([String: Int].self, forKey: .iceCreams)

var realDictionary: [IceCream: Int] = [:]

for key, value in manualDictionary {
    guard let iceCream = IceCream(rawValue: key) else { continue }
    realDictionary[iceCream] = value
}

self.iceCreams = realDictionary

But that's not working (it won't let me decode it as a [String: Int]).

@christianselig
Copy link
Author

Thanks y'all @jegnux @eliyap @damir @quinwoods this helped a ton :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment