Print All Keys in a Swift Dictionary
Use the keys property to access every key in a Swift dictionary. You can iterate over dictionary.keys directly, convert the keys to an array, or sort them before printing when the output order matters.
To print all the keys of a dictionary, we can iterate over the keys returned by Dictionary.keys or iterate through each (key, value) pair of the dictionary and then access the key alone.
Swift Dictionary.keys Syntax
The keys property returns a Dictionary<Key, Value>.Keys collection. It contains every key in the dictionary, but it is not a standard Swift Array.
for key in dictionary.keys {
print(key)
}
If another API requires an array, create one with Array(dictionary.keys).
Example 1 – Get all keys in a Swift Dictionary
In this example, we will create a Swift Dictionary with some initial values and print all the keys of the Dictionary.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
for key in myDictionary.keys {
print("\(key)")
}
Output
Raghu
John
Mohan
Here, myDictionary.keys returns a view of the dictionary’s keys. The for loop visits each key and prints it.
A Swift dictionary does not provide a fixed key order. The same program may print the names in a different order. Sort the keys when you need predictable output.
Print Swift Dictionary Keys in Sorted Order
When the key type conforms to Comparable, call sorted() on the keys collection before printing it.
let myDictionary: [String: Int] = [
"Mohan": 75,
"Raghu": 82,
"John": 79
]
for key in myDictionary.keys.sorted() {
print(key)
}
Output
John
Mohan
Raghu
Example 2 – Print all keys in a Swift Dictionary using for loop
In this example, we will create a Swift Dictionary with some initial values and print all the keys of the Dictionary.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
for (key, value) in myDictionary {
print("\(key)")
}
Output
Raghu
John
Mohan
In this example, we used a for loop to iterate over the (key, value) pairs of the Dictionary.
You might get a warning that value has not been used inside the loop. You can suppress this warning by using an underscore _ in the place of value.
for (key, _) in myDictionary {
print(key)
}
Use this pattern when you are already iterating over dictionary entries but only need the key. When no values are needed at all, iterating over myDictionary.keys is more direct.
Convert Swift Dictionary Keys to an Array
Use the Array initializer when you need a value of type [Key] rather than the dictionary’s keys view.
let myDictionary: [String: Int] = [
"Mohan": 75,
"Raghu": 82,
"John": 79
]
let keyArray: [String] = Array(myDictionary.keys)
print(keyArray)
The array follows the dictionary’s current iteration order. Use myDictionary.keys.sorted() when you want a sorted [String] result.
Print a Specific Swift Dictionary Key and Its Value
A dictionary is accessed by key rather than by numeric position. If you already know the key, use it to look up the corresponding value. Dictionary lookup returns an optional because the key may not exist.
let myDictionary = ["Mohan": 75, "Raghu": 82, "John": 79]
let selectedKey = "Raghu"
if let value = myDictionary[selectedKey] {
print("\(selectedKey): \(value)")
} else {
print("Key not found")
}
Output
Raghu: 82
Example 3 – Print all keys in a Swift Dictionary along with an index/offset
In this example, we will create a Swift Dictionary with some initial values and print all the keys of the enumerated Dictionary.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
for (item) in myDictionary.enumerated() {
print("\(item.offset): \(item.element.key)")
}
Output
0: Mohan
1: John
2: Raghu
Each item in the enumerated dictionary has the structure of
(offset: 0, element: (key: "Mohan", value: 75))
So, when you iterate over an enumerated dictionary, you will get offset and the element for each iteration. Which is why we used item.element.
As we need to get the key only, we have specifically used item.element.key .
The offset is produced by enumerated(); it is not a permanent index assigned to that dictionary key. Because dictionary iteration order is not fixed, do not store or rely on this offset as the identity of an entry.
Print Swift Dictionary Keys with forEach
The forEach method provides another way to print every key. A regular for loop is usually clearer when you need break, continue, or additional control flow.
let myDictionary = ["Mohan": 75, "Raghu": 82, "John": 79]
myDictionary.keys.forEach { key in
print(key)
}
Swift Dictionary Key Printing Mistakes to Avoid
- Treating
dictionary.keysas an array: it is a dictionary keys collection. Wrap it inArray(...)only when an array is required. - Expecting insertion or alphabetical order: sort the keys explicitly before printing them.
- Using an integer offset to identify a key: dictionary offsets can change when iteration order changes.
- Ignoring an unused value warning: replace the unused value with
_, or iterate overdictionary.keys. - Force-unwrapping a value lookup: use optional binding when the requested key might be absent.
Swift Dictionary Keys FAQs
How do I get all keys from a dictionary in Swift?
Use dictionary.keys. Iterate over the returned collection directly, or use Array(dictionary.keys) when you specifically need an array.
How do I print Swift dictionary keys in alphabetical order?
For string keys, iterate over dictionary.keys.sorted(). This creates a sorted array of keys before printing them.
How do I get a Swift dictionary key by index?
Dictionaries are designed for key-based lookup and do not provide a stable numeric index for entries. Convert or sort the keys first if a temporary positional array is required.
How do I print both the key and value in a Swift dictionary?
Iterate over the dictionary with for (key, value) in dictionary, then print both variables. Sort the entries first if their display order must be predictable.
Swift Dictionary Keys Editorial QA Checklist
- State that
Dictionary.keysreturns a keys collection, not a standard array. - Warn that dictionary iteration order should not be treated as fixed.
- Use
sorted()in examples that promise alphabetical or predictable output. - Use
_when a loop ignores the dictionary value. - Clarify that
enumerated()offsets are temporary and are not stable dictionary indexes. - Use optional binding when demonstrating lookup for a specific key.
Choosing a Swift Dictionary Key Printing Method
Use dictionary.keys for direct iteration, dictionary.keys.sorted() for predictable output, and Array(dictionary.keys) when another operation requires an array. In this Swift Tutorial, we learned how to print keys directly, print them with offsets, sort them, and access a value for a known key.
TutorialKart.com