【发布时间】:2018-03-06 15:51:13
【问题描述】:
我有示例 A 对象应该是 Decodable:
class A: Decodable {
class B: Decodable {
let value: Int
}
let name: Date
let array: [B]
}
然后我有 ADecoder 的子类 Decoder 对象:
class ADecoder: Decoder {
let data: [String: Any]
// Keyed decoding
public func container<Key>(keyedBy type: Key.Type)
throws -> KeyedDecodingContainer<Key> where Key: CodingKey {
return KeyedDecodingContainer(AKeyedDecoding(data))
}
// ...
}
其中使用AKeyedDecoding键控解码容器:
class AKeyedDecoding<T: CodingKey> : KeyedDecodingContainerProtocol {
typealias Key = T
let data: [String: Any]
func decode<T>(_ type: T.Type, forKey key: Key)
throws -> T where T: Decodable {
if type == Date.self {
// Parse date, for example
}
// Not called:
if type == Array<Decodable>.self {
// Decode array of `Decodable`s
}
}
// Rest of protocol implementations...
}
解码过程:
let values = ["name": "Hello" as AnyObject, "array": ["value": 2] as AnyObject]
let decoder = ADecoder(data: values)
do {
try A(from: decoder)
} catch {
print(error)
}
这适用于具有自定义 Date 数据类型的 name 字段。
但我一直在解码 B 对象的数组。
有人知道如何实现它或从哪里获得更多信息?
- 如何检查
T.type是否是Array的Decodables? - 如何解码?
【问题讨论】: