Swift: Converting a Dictionary into an Array

Updated: May 8, 2023 By: Khue Post a comment

In Swift, there are several ways to convert a dictionary into an array depending on what you want to get from the dictionary. Let’s see the following code examples for more clarity.

Using the keys or values property

If you want to get an array of all the keys in the dictionary, you can use the keys property, which returns a collection of the dictionary’s keys. Another thing to do is to use the Array initializer to create an array from this collection.

Example:

let dict = [
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
]

let allKeys = Array(dict.keys)
print(allKeys)

Output:

["key1", "key3", "key2"]

In case the result you need is an array that contains all values of the input dictionary, just use the values property in combination with the Array initializer like so:

let dict = [
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
]

let allValues = Array(dict.values)
print(allValues)

Output:

["value1", "value3", "value2"]

Using the map() method

If you want to produce an array whose each element is a mix of a key and the associated value from a given dictionary, you can use the map() method, which applies a transformation to each element of a collection and returns a new collection.

Example:

// a dictionary of people and their ages
let people = [
    "Anna": 67,
    "Beto": 8,
    "Jack": 33,
    "Sam": 25,
    "Sara": 54,
    "Sue": 10,
    "Tom": 18,
]

// create an array of sentences describing each person
let sentences = people.map { name, age -> String in
    "\(name) is \(age) years old."
}

print(sentences)

Output:

["Sam is 25 years old.", "Jack is 33 years old.", "Anna is 67 years old.", "Sara is 54 years old.", "Sue is 10 years old.", "Beto is 8 years old.", "Tom is 18 years old."]

By using this approach, you can create results with complex calculations and customizations.