arrays - 在没有 for 循环的情况下快速从字典转换为数组

标签 arrays swift dictionary functional-programming reduce

我有一些从服务器返回的数据,如下所示:

let returnedFromServer = ["title" : ["abc",  "def",  "ghi"],

                      "time"  : ["1234", "5678", "0123"],

                      "content":["qwerty", "asdfg", "zxcvb"]]

我想把它改造成这样的:

let afterTransformation =

[["title" : "abc",
  "time"  : "1234",
 "content": "qwerty"],

["title" : "def",
 "time"  : "5678",
"content": "asdfg"],

["title" : "ghi",
 "time"  : "0123",
"content": "zxcvb"]]

我目前的实现如下:

var outputArray = [[String : AnyObject]]()

for i in 0..<(returnedFromServer["time"] as [String]).count {

        var singleDict = [String: AnyObject]()

        for attribute in returnedFromServer {

            singleDict[attribute] = returnedFromServer[attribute]?[i]
        }
        outputArray.append(singleDict)
}

这很好用,但我认为这不是一个非常优雅的解决方案。鉴于 Swift 具有一些巧妙的功能,例如 reducefilterma​​p,我想知道我是否可以在不显式使用循环的情况下完成同样的工作.

感谢您的帮助!

最佳答案

使用思路和字典扩展

extension Dictionary {
    init(_ pairs: [Element]) {
        self.init()
        for (k, v) in pairs {
            self[k] = v
        }
    }

    func map<OutKey: Hashable, OutValue>(transform: Element -> (OutKey, OutValue)) -> [OutKey: OutValue] {
        return Dictionary<OutKey, OutValue>(Swift.map(self, transform))
    }
}

来自

你可以用

let count = returnedFromServer["time"]!.count
let outputArray = (0 ..< count).map {
    idx -> [String: AnyObject] in
    return returnedFromServer.map {
        (key, value) in
        return (key, value[idx])
    }
}

关于arrays - 在没有 for 循环的情况下快速从字典转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27635981/

相关文章:

python - 没有默认方法的对寄存器数组进行排序

c - 数组指针两种声明类型的差异

sql - 您可以使用 SQL 从 JSON 数组中选择值吗?

ios - 更改 UIImagePickerController 标签的字体

python - 从列表和逗号分隔行创建 python 字典

Case 标签不会缩减为 C 中的整数常量?

SwiftUI - 隐藏 ScrollView 的指示器使其停止滚动

swift - PFGeoPoint 不适用于 xcode7-ios9

dictionary - map 与 mapM 行为

java - 使用接口(interface)实例化和具体类实例化之间的区别? (HashMap、Map & List、ArrayList)