How do I convert data dictionary into an array Swift?

此生再无相见时 提交于 2020-01-17 08:11:41

问题


I'm retrieving firebase data back as a dictionary of dictionary:

 guard let data = snapshot.value as? [String: [String:Int]] else {

And I'm trying to retrieve the first key(?) as in if it comes back as a result like this:

 "café-veritas": ["AmpleSeating": 1, "Organic": 1, "Quiet": 1, "AmpleOutletAccess": 1, "Couch": 1, "Loud": 1, "GlutenFree": 1, "FreeWifi": 1], 
 "cafe-myriade": ["Terasse": 1, "LaptopFriendly": 1, "Quiet": 1, "FreeWifi": 1, "FastWifi  ": 1, "GlutenFree": 1],

I'm trying to put the name of the cafes, "café-veritas" and "cafe-myriade" into an array. I'm told to use the map function but I'm not sure how. Would it be like this?

 let array = data.map { yelp IDs in yelpIDs}

I'm basically trying to get the key back so that all it is is just the cafe name. Thanks!


回答1:


About using map, I guess this page is helpful and visual.

let names = data.map { return $0.key }
print(names)    // prints ["café-veritas", "cafe-myriade"]



回答2:


Here is an example how you can achieve it:

var data : [String: [String:Int]]

data = ["first": ["value1": 1], "second": ["value2": 1]]

var array = data.map { $0.value }
var arr = array.flatMap { $0.keys.first }

print(arr)

Will print:

["value2", "value1"]



回答3:


calling your resulting dictionary "dictionaries", you could do something like this:

let dictionaries = [["café-veritas": ["AmpleSeating": 1, "Organic": 1, "Quiet": 1, "AmpleOutletAccess": 1, "Couch": 1, "Loud": 1, "GlutenFree": 1, "FreeWifi": 1],"cafe-myriade": ["Terasse": 1, "LaptopFriendly": 1, "Quiet": 1, "FreeWifi": 1, "FastWifi  ": 1, "GlutenFree": 1]]]

let result = dictionaries.flatMap({ $0.keys.map({ $0 }) })

// returns ["café-veritas", "cafe-myriade"]


来源:https://stackoverflow.com/questions/45446758/how-do-i-convert-data-dictionary-into-an-array-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!