Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dictionary
swift
keys
communitycreator

How to get all keys of the Dictionary in Swift

Programming Bytes

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)")
Get all the keys of the Dictionary

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.

RELATED TAGS

dictionary
swift
keys
communitycreator
RELATED COURSES

View all Courses

Keep Exploring