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.
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)")
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
.