声明符合协议的未知类型的变量?

时间:2019-09-19 19:46:52

标签: swift protocols concreteclass

是否可以声明符合一个或多个协议的未知具体类型的变量?

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)

0 个答案:

没有答案