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

前端之家收集整理的这篇文章主要介绍了数组 – 在没有for循环的情况下在swift中从字典转换为数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一些从服务器返回的数据,如下所示:

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

猜你在找的Swift相关文章