如何将符合Codable协议的对象数组转换为Dictionary数组?

时间:2018-08-03 08:45:48

标签: swift dictionary codable

我有一个类似的结构:

struct Demo: Codable {
    var foo: String
    var bar: String
    ...
}

我有一系列演示:

let array = [Demo(foo: "a", bar: "b"), Demo(foo: "c", bar: "d")]

我想将此数组转换为具有以下内容的字典[[String:Any]]:

let dictionary:[[String : Any]] = array.toDictionaryFromArrayOfCodable()

我如何得到它?

编辑: 我的预期输出是类似的,并且我想使用JSONEncoder:

[["foo": "a", "bar": "b"], ["foo": "c", "bar": "d"]]

1 个答案:

答案 0 :(得分:1)

我找到了使用两个扩展名的解决方案: -首先从对象获取字典 -其次,使用第一个扩展名,用每个数组元素创建一个字典数组:

用法:

let dictionary = [Demo].asDictionaryFromArray()
print(dictionary)

预期输出: [[“ bar”:b,“ foo”:a],[“ bar”:d,“ foo”:c]]

extension Encodable {

    var dictionaryFromObject: [String: Any]? {
        guard let data = try? JSONEncoder().encode(self) else { return nil }
        return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
    }

}

extension Array where Element: Encodable {

    func asDictionaryFromArray() -> [[String: Any]] {
        var dict = [[String: Any]]()

        _ = self.map {
            if let objectDict = $0.dictionaryFromObject {
                dict.append(objectDict)
            }
        }

        return dict
    }

}