How to get all keys of the Dictionary in Swift

The Swift Dictionary’s keys property gets all the keys present. The keys property will return a collection only containing keys of the Dictionary.

The order of keys in the returned collection is the same as the order of key-value pairs present in the Dictionary.

Code

The code below demonstrates how to get all the keys present in the Dictionary:

import Swift
//create a Dictionary
var numbers:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
// print the Dictionary
print("The numbers dictionary is \(numbers)")
// print the keys of the Dictionary
var keys = numbers.keys
print("\nThe keys of numbers dictionary is: \(keys)")

Explanation

  • Line 4: We create a new Dictionary named numbers. The numbers Dictionary can have the Int type as a key and the String type as a value.

  • Line 7: We print the numbers Dictionary.

  • Line 10: We access the keys property of the Dictionary and store it in the keys variable. It will have all the Dictionary’s keys.

  • Line 11: Prints the keys.

Free Resources