我有样本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)
}
这适用于name
具有自定义Date
数据类型的字段。但我被困在解码B
对象数组中。
有人知道如何实施它或从哪里获得更多信息?
- 如何检查是否是
T.type
s ?Array
Decodable
- 如何解码它们?