GoldenJoe
GoldenJoe

Reputation: 8002

Declaring a variable of unknown type that conforms to a protocol?

Is it possible to declare a variable of an unknown concrete type that conforms to one or more protocols?

class A: Codable {
    ...
}
class B: Codable {
    ...
}
class Serializer {
    static func serializeFromJSON<T>(type: T.Type, dict: [String:Any]) throws -> T where T: Decodable { ... }
    static func serializeToJSON<T>(_ value: T) throws -> Data where T: Encodable { ... }
}

let dict : [String:Any] = ["Someval":1] // or whatever junk data
let myObj : [???] // what goes here?
switch someval {
case a: myObj = Serializer.serializeFromJSON(type: ClassA.self, dict)
case b: myObj = Serializer.serializeFromJSON(type: ClassB.self, dict)
}
let JSONEncoder = Serializer.serializeToJSON(myObj)

Upvotes: 0

Views: 454

Answers (0)

Related Questions