【发布时间】:2020-12-07 01:51:45
【问题描述】:
我创建了一个自定义Decoder,它可以解码非常具体的数据格式,遵循this tutorial。
请注意,我的数据格式不是 XML 或 JSON。
我开始:
public final class MyDecoder: Decoder {
public var codingPath: [CodingKey] = []
public var userInfo: [CodingUserInfoKey:Any] = [:]
public let input: String
public init(_ input: String) {
self.input = input
}
// all stubs are below
并添加了协议所需的所有存根。然后,跟着视频,我还添加了一个符合KeyedDecodingContainerProtocol的struct,并在decode(_ type: String.Type, forKey key: Key)中填写了所需的解析。
为了获取信息,我这样做:
let decoder = MyDecoder(input)
let info = try! myRecord(from: decoder)
到目前为止效果很好。
接下来我想做的是看看是否可以像 JSONDecoder 那样做:
let decoder = MyDecoder()
guard let info = try? decoder.decode(MyInfo.self, from: input) else {
fatalError("Failed to decode data")
}
但这当然行不通,因为MyDecoder 没有decode() 函数。
所以,我的问题是,如果我添加这个功能,应该在里面放什么?
【问题讨论】:
-
您可以查看the implementation of
JSONDecoder以更好地了解其工作原理,但一般而言,您编写的符合Decoder的类型通常是not 实现decode(_:from:)的顶级类型。Decoder用于解码的“中间”和“底层”级别,但顶层接口不同。JSONDecoder使用私有_JSONDecoder类作为其实际的Decoder实例。 -
换句话说,本教程为您提供了一个有效的
Decoder实现,但您可能希望将其包装在另一种类型中以提供不同的 API 表面,即 不是 在实际init(from:)期间可访问。