Home > Software design >  Is it possible to pass multiple data types inside a JsonDecoder?
Is it possible to pass multiple data types inside a JsonDecoder?

Time:09-24

Here's what I intend to do.

I have two structs, StructA and StructB.

I also have a JsonDecoder that needs to accept either StructA or StructB.

I've tried defining a common protocol and conforming both structs to that protocol and tried using the some keyword like:

struct StructA: CommonStruct {
   let someBool = false
}

struct StructB: CommonStruct {
   let someString = "SomeString"
}

protocol CommonStruct {
}

func needToGetShitDone(
   data: CommonStruct  // <- What type should ``data`` be? 
) {
   let data = try JsonDecoder().decode(CommonStruct.type, from: data)
}

...but of course, that didn't work.

Is it possible to configure the JsonDecoder to accept both StructA and StructB.

CodePudding user response:

Make the protocol conform to Decodable and use a generic function

protocol CommonStruct: Decodable {}


func decode<T: CommonStruct>(from data: Data) throws -> T {
    try JSONDecoder().decode(T.self, from: data)
}

Or if you have no other use for your protocol then you can skip it and do

func decode<T: Decodable>(from data: Data) throws -> T {
    try JSONDecoder().decode(T.self, from: data)
}
  • Related