解码可为空的异构字典

时间:2020-06-09 15:56:07

标签: swift codable

我需要解码[(Heterogeneous object): CGFloat]?形式的字典。我在KeyedDecodingContainer上有一些有效的扩展名,这些扩展名使我可以解码单个异类对象的列表,但是我正努力将其转换为与词典一起使用。这是可选数组的工作方法:

func decodeArrayIfPresent<T : Decodable, U : ClassFamily>(family: U.Type, forKey key: K) throws -> [T]? {
    do {
        var container = try self.nestedUnkeyedContainer(forKey: key)
        var list = [T]()
        var tmpContainer = container
        while !container.isAtEnd {
            let typeContainer = try container.nestedContainer(keyedBy: Discriminator.self)
            let family: U? = try typeContainer.decodeIfPresent(U.self, forKey: U.discriminator)
            if let type = family?.getType() as? T.Type {
                list.append(try tmpContainer.decode(type))
            }
        }
        return list
    } catch DecodingError.keyNotFound {
        return nil
    } catch DecodingError.valueNotFound {
        return nil
    }
}

这是我要去字典的地方:

func decodeDictIfPresent<T : Decodable, U : ClassFamily>(family: U.Type, forKey key: K) throws -> [T: Any]? {
    do {
        var container = try self.nestedUnkeyedContainer(forKey: key)
        var dict = [T: Any]()
        var tmpContainer = container
        while !container.isAtEnd {
            let typeContainer = try container.nestedContainer(keyedBy: Discriminator.self)
            let family: U? = try typeContainer.decodeIfPresent(U.self, forKey: U.discriminator)
            if let type = family?.getType() as? T.Type {
                list.append(try tmpContainer.decode(type))
            }
        }
        return dict
    } catch DecodingError.keyNotFound {
        return nil
    } catch DecodingError.valueNotFound {
        return nil
    }
}

要求:

protocol ClassFamily: Decodable {
    /// The discriminator key.
    static var discriminator: Discriminator { get }

    /// Returns the class type of the object coresponding to the value.
    func getType() -> AnyObject.Type
}

/// Discriminator key enum used to retrieve discriminator fields in JSON payloads.
enum Discriminator: String, CodingKey {
    case type = "type"
}

任何朝着正确方向的指针将不胜感激!预先感谢

0 个答案:

没有答案