是否可以声明符合一个或多个协议的未知具体类型的变量?
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)