How to convert dictionary to array How to convert dictionary to array ios ios

How to convert dictionary to array


You can use a for loop to iterate through the dictionary key/value pairs to construct your array:

var myDict: [String : Int] = ["attack" : 1, "defend" : 5, "block" : 12]var arr = [String]()for (key, value) in myDict {    arr.append("\(key) \(value)")}

Note: Dictionaries are unordered, so the order of your array might not be what you expect.


In Swift 2 and later, this also can be done with map:

let arr = myDict.map { "\($0) \($1)" }

This can also be written as:

let arr = myDict.map { "\($0.key) \($0.value)" }

which is clearer if not as short.


The general case for creating an array out of ONLY VALUES of a dictionary in Swift 3 is (I assume it also works in older versions of swift):

let arrayFromDic = Array(dic.values.map{ $0 })

Example:

let dic = ["1":"a", "2":"b","3":"c"]let ps = Array(dic.values.map{ $0 })print("\(ps)")for p in ps {    print("\(p)")}


If you like concise code and prefer a functional approach, you can use the map method executed on the keys collection:

let array = Array(myDict.keys.map { "\($0) \(myDict[$0]!)" })

or, as suggested by @vacawama:

let array = myDict.keys.array.map { "\($0) \(myDict[$0]!)" }

which is functionally equivalent