【发布时间】:2019-02-25 21:10:31
【问题描述】:
使用Codable,我可以创建以下扩展
extension Decodable {
public static func decode(data: Data, decoder: JSONDecoder = .default) -> Self? {
do {
return try decoder.decode(self, from: data)
} catch let error as NSError {
CodableKit.log(message: "\(error.userInfo)")
return nil
}
}
}
并在单个对象和数组类型上使用它,例如
let person = Person.decode(data: personData) // single
let people = [Person].decode(data: peopleData) // array
上面的 2 行编译没有问题。
现在,我想创建一个类似于Codable 的新协议
public typealias JsonCodable = JsonDecodable & JsonEncodable
public protocol JsonDecodable: Decodable {
static func decode(data: Data?, decoder: JSONDecoder) -> Self?
}
extension JsonDecodable {
static func decode(data: Data?, decoder: JSONDecoder) -> Self? {
....
}
}
当我尝试像使用 Codable 一样使用 JsonDecodable 时,我收到以下编译器错误
类型“[Person]”没有成员“decode”;
let person = Person.decode(data: personData) // this works
let people = [Person].decode(data: peopleData) // this does not
如何让JsonDecodable 以与扩展Codable 时相同的方式解码为模型数组?
【问题讨论】:
-
与你的问题无关,但你应该让你的方法抛出,删除 do catch 并返回一个非可选的
public static func decode(data: Data, decoder: JSONDecoder = .default) throws -> Self { return try decoder.decode(self, from: data) } -
@LeoDabus 注意到。
标签: swift protocols codable swift4.2