【问题标题】:Why does my special Codable protocol work differently than Swift's Codable with Array?为什么我的特殊 Codable 协议与 Swift 的 Codable with Array 的工作方式不同?
【发布时间】: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


【解决方案1】:

如果错误消息使用不加糖的类型名,它可能会更有用:

类型 'Array' 没有成员 'decode';

Person 可能符合您的协议,但Array 不符合。 Swift 明确声明 Arrays 是 Decodable 如果它们的元素是。你只需要这样做:

extension Array : JsonDecodable where Element : JsonDecodable {
    static func decode(data: Data?, decoder: JSONDecoder) -> Self? {
        // Decode each element and return an array
    }
}

这使用了一个名为"Conditional Conformance" 的功能,它允许容器通常符合协议,如果它们持有的类型也符合的话。

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 2018-11-09
    • 2018-09-27
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    相关资源
    最近更新 更多