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 Dictionaryvar numbers:[Int:String] = [1:"One", 2:"Two", 3:"Three"]// print the Dictionaryprint("The numbers dictionary is \(numbers)")// print the keys of the Dictionaryvar keys = numbers.keysprint("\nThe keys of numbers dictionary is: \(keys)")
Explanation
-
Line 4: We create a new
Dictionarynamednumbers. ThenumbersDictionary can have theInttype as a key and theStringtype as a value. -
Line 7: We print the
numbersDictionary. -
Line 10: We access the
keysproperty of the Dictionary and store it in thekeysvariable. It will have all the Dictionary’s keys. -
Line 11: Prints the
keys.