我有两个structs
,符合相同的protocol
。现在我想解析一些包含两种类型的JSON,并自动init
具体类型(struct
)并将所有内容放在协议类型的通用数组中。
到目前为止我得到了什么:
protocol JSONSerializable {
init?(json: [String: Any?])
}
protocol General: JSONSerializable { ... }
struct ConcreteA: General {
init?(json: [String: Any?]) { ... }
...
}
struct ConcreteB: General {
init?(json: [String: Any?]) { ... }
...
}
func parse(json: [String: Any?]) -> [General]? {
// I want this to work generic like:
return jsonDicts.flatMap { General(json: $0) } // Error: Protocol type ' General' cannot be instantiated
// But the only way I got it working is like this, which is not really generic ;-)
return jsonDicts.flatMap {
if let concreteA = ConcreteA(json: $0) {
return concreteA
}
if let concreteB = ConcreteB(json: $0) {
return concreteB
}
return nil
}
}
那么你能给我任何提示或建议我如何达到预期的行为吗?