当前位置 : 主页 > 手机开发 > 其它 >

数组 – 在没有for循环的情况下在swift中从字典转换为数组

来源:互联网 收集:自由互联 发布时间:2021-06-11
我有一些从服务器返回的数据,如下所示: let returnedFromServer = ["title" : ["abc", "def", "ghi"], "time" : ["1234", "5678", "0123"], "content":["qwerty", "asdfg", "zxcvb"]] 我想把它变成这样的东西: let afterTran
我有一些从服务器返回的数据,如下所示:

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有一些简洁的功能,如reduce,filter和map,我想知道如果没有明确地使用循环我是否可以做同样的工作.

谢谢你的帮助!

使用想法和字典扩展

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))
    }
}

> What’s the cleanest way of applying map() to a dictionary in Swift?,

你可以实现这个目标

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