Home > Software engineering >  Is there a way to extract arbitrary data from a Swift decoder?
Is there a way to extract arbitrary data from a Swift decoder?

Time:09-12

Here's the deal : I'm making a level editor for a game, and I'd like to try to support modded content. Is there some way, when initialising from a Decoder, that I could ask it to "Give me the rest of the data" ?

Something like :

var json = "{\"name\" : \"test\", \"modData\" : 35}"

struct Something : Codable {
    var name : String
    var additional : [String : any Codable] // Possibly the wrong type

    private enum CodingKeys : String, CodingKey {
        case name, additional
    }

    init(from decoder : Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = container.decode(String.self, forKey: .name)
        additional = //Is there any way to get modded data out here ?
    }
}

The idea being that modData is something I couldn't possibly have known about when implementing the thing, but I still retain some level of compatibility with like showing it in the inspector and allowing you to change its value.

I'm almost certain this is impossible, but maybe I'm missing something.

CodePudding user response:

You can make the struct generic, the compiler creates CodingKeys and the init method on your behalf.

struct Something<T: Decodable> : Decodable {
    var name : String
    var additional : T
}

But at the moment you are going to use it you must specify the static type of T. It can be anything, a single value or a collection type which conforms to Decodable.

  • Related