Convert a Swift Dictionary to Arrays of Keys and Values
In Swift, a dictionary exposes its keys through dictionary.keys and its values through dictionary.values. These properties return collection views named Dictionary.Keys and Dictionary.Values. To create independent Swift arrays, pass those views to the Array initializer.
If you need the reverse operation, see how to create a dictionary using arrays.
Swift Dictionary Keys and Values Syntax
The following syntax accesses the dictionary’s key and value collections:
var myDictionary:[keyType:valueType] = [key1:value1, key2:value1]
var keys = myDictionary.keys
var values = myDictionary.values
Here, keys is a Dictionary<Key, Value>.Keys collection and values is a Dictionary<Key, Value>.Values collection. Their elements have the dictionary’s Key and Value types, but the collections themselves are not Array values.
Use the following form when the result must be an array:
let keyArray = Array(myDictionary.keys)
let valueArray = Array(myDictionary.values)
Get Key and Value Collections from a Swift Dictionary
In this example, we create a dictionary with student names as keys and scores as values. The program then iterates over the key and value collections separately.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
var keys = myDictionary.keys
var values = myDictionary.values
print("keys\n-------")
for key in keys {
print("\(key)")
}
print("\nvalues\n-------")
for value in values {
print("\(value)")
}
Output
keys
-------
Mohan
John
Raghu
values
-------
75
79
82
A Swift dictionary does not guarantee a stable iteration order. The same keys and values may therefore appear in a different order when the program runs. Sort the data when your output or later processing requires a predictable order.
Convert Dictionary.Keys and Dictionary.Values to Swift Arrays
The Array initializer copies the elements from each dictionary view into a standard Swift array.
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]
let names: [String] = Array(scores.keys)
let marks: [Int] = Array(scores.values)
print(type(of: names))
print(type(of: marks))
Output
Array<String>
Array<Int>
Explicit type annotations are optional because Swift can infer [String] and [Int] from the dictionary.
Convert a Swift Dictionary to an Array of Key-Value Pairs
Converting keys and values into separate arrays can lose the visible relationship between each key and its value. When that relationship must be retained, convert the dictionary itself into an array of labeled tuples.
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]
let entries: [(key: String, value: Int)] = Array(scores)
for entry in entries {
print("\(entry.key): \(entry.value)")
}
Each array element contains a matching key and value. The order of the tuple array still follows the dictionary’s current iteration order.
Sort Swift Dictionary Keys, Values, or Key-Value Pairs
Use sorted() when the element type conforms to Comparable. To sort dictionary entries by key or value, provide a closure.
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]
let sortedNames = scores.keys.sorted()
let sortedMarks = scores.values.sorted()
let entriesByName = scores.sorted { $0.key < $1.key }
let entriesByScore = scores.sorted { $0.value < $1.value }
print(sortedNames)
print(sortedMarks)
print(entriesByName)
Sorting keys and values independently is suitable only when you need separate lists. It does not preserve positional pairing between the two resulting arrays. Sort the dictionary entries instead when each key must remain associated with its value.
Transform Swift Dictionary Values with mapValues()
If the goal is to modify every value while keeping the same keys, use mapValues() instead of converting the dictionary to arrays.
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]
let resultLabels = scores.mapValues { score in
score >= 80 ? "Distinction" : "Pass"
}
print(resultLabels)
mapValues() returns another dictionary with the original keys and transformed values. Use map or Array(dictionary) when the required result is an array.
Common Swift Dictionary-to-Array Mistakes
- Assuming
dictionary.keysis already an array: wrap it withArray(...)when an API specifically requires[Key]. - Relying on dictionary order: call
sorted()or sort the key-value pairs before displaying or comparing them. - Sorting keys and values separately when pairing matters: sort dictionary entries so each key remains attached to its value.
- Using an array as a dictionary key: Swift dictionary keys must conform to
Hashable. Standard Swift arrays do not conform toHashable, so they cannot be used directly as dictionary keys. - Converting data unnecessarily: iterate over
keys,values, or the dictionary directly when no independent array is needed.
Swift Dictionary to Array FAQs
How do I convert a dictionary to an array in Swift?
Use Array(dictionary) to produce an array of (key: Key, value: Value) tuples. Use Array(dictionary.keys) or Array(dictionary.values) when you need only keys or only values.
How do I get all keys from a Swift dictionary?
Access dictionary.keys to get the keys collection. Convert it with Array(dictionary.keys) when a standard array is required.
Does a Swift dictionary preserve key and value order?
Do not depend on a dictionary’s iteration order. Sort the keys, values, or key-value pairs when your code requires predictable ordering.
Can an array be used as a Swift dictionary key?
A dictionary key must conform to Hashable. Swift’s standard Array type does not conform to Hashable, so an array cannot be used directly as a dictionary key.
Swift Dictionary Conversion QA Checklist
- Confirm whether the result should be a keys array, a values array, or an array of key-value tuples.
- Use
Array(dictionary.keys)andArray(dictionary.values)only when independent arrays are required. - Do not describe
Dictionary.KeysorDictionary.Valuesas arrays unless they have been converted. - Sort the result whenever examples, tests, or user interfaces require predictable ordering.
- Keep key-value pairs together when their association is required by later processing.
Choosing the Correct Swift Dictionary Conversion
Use dictionary.keys and dictionary.values for direct collection access, wrap those collections with Array for independent arrays, and use Array(dictionary) when every key must stay paired with its value. For more Swift examples, visit the Swift Tutorial.
TutorialKart.com