1

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!

Sam
  • 495
  • 3
  • 11
  • 19
  • 2
    If you're after an array of keys of a dictionary, use the `keys` property, like this: `Array(a.keys)`. To get the first one, it's `Array(a.keys).first` – paulvs Aug 01 '17 at 20:12
  • 1
    Possible duplicate of [Array from dictionary keys in swift](https://stackoverflow.com/questions/26386093/array-from-dictionary-keys-in-swift) – Kymer Aug 01 '17 at 20:21

3 Answers3

5

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"]
Durdu
  • 4,649
  • 2
  • 27
  • 47
0

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"]
fiks
  • 1,045
  • 9
  • 21
0

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"]
RyanP
  • 11
  • 1