首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >KeyedDecodingContainer解码内部可解码对象

KeyedDecodingContainer解码内部可解码对象
EN

Stack Overflow用户
提问于 2018-03-06 15:51:13
回答 1查看 1.3K关注 0票数 1

我有示例A对象,应该是Decodable

代码语言:javascript
复制
class A: Decodable {
    class B: Decodable {
        let value: Int
    }
    let name: Date
    let array: [B]
}

然后,我有ADecoder子类的Decoder对象,用于:

代码语言:javascript
复制
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键控解码容器:

代码语言:javascript
复制
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...
}

解码过程:

代码语言:javascript
复制
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是否是Array of Decodables?
  • 如何破译?
EN

回答 1

Stack Overflow用户

发布于 2018-03-06 18:49:45

对于数组,您需要提供一个unkeyedContainer()方法,该方法用于从位置容器中解码值。

代码语言:javascript
复制
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
}

请注意,您还需要提供一个singleValueContainer()来解码leafs (最深属性级别)。

代码语言:javascript
复制
func singleValueContainer() throws -> SingleValueDecodingContainer {
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49134932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档