Swift – Print Dictionary Keys

Welcome to Swift Tutorial. In this tutorial, we will learn how to print all the keys present in a dictionary.

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.

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

In this example, myDictionary.keys returns an array with all the keys in it. And we used a for loop to iterate over the keys String array.

ADVERTISEMENT

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.

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 .

Conclusion

In this Swift Tutorial, we learned how to print keys of a Dictionary using Dictionary.keys.