[英]How do I convert data dictionary into an array Swift?
I'm retrieving firebase data back as a dictionary of dictionary: 我正在将Firebase数据作为字典的字典检索:
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. 我正在尝试将咖啡馆的名称“café-veritas”和“ cafe-myriade”放入一个数组中。 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!
谢谢!
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"]
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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.