Swift .keys
Published Sep 29, 2024
Contribute to Docs
In Swift, the .keys property of a dictionary returns an unordered collection containing all the keys within the dictionary. Since this collection is unordered, the order of the keys may vary each time they are accessed. This property is part of the Dictionary structure and is useful when iterating through or manipulating only the keys of a dictionary.
Syntax
dictionaryName.keys
dictionaryName: The instance of a dictionary from which the keys are to be accessed.
Note: The
keysproperty returns a collection, not an array, however, it can be converted to an array using the Array() initializer if needed.
Example
In the following example, the keys property is used to access and print all the keys in the studentGrades dictionary:
var studentGrades = ["Jon": 84, "Nic": 95, "Mary": 88]// Print the keys as a Dictionary.Keys collectionprint(studentGrades.keys)// Convert the keys collection to an array for index-based accesslet keysArray = Array(studentGrades.keys)// Access the first key in the arrayprint(keysArray[0])
The output for the above code is:
["Jon", "Nic", "Mary"]Jon
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Swift on Codecademy
- Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
- Includes 7 Courses
- With Certificate
- Beginner Friendly.13 hours
- A powerful programming language developed by Apple for iOS, macOS, and more.
- Beginner Friendly.12 hours