The keys
property returns just the keys of the dictionary.
Example
var languages = ["Swift": 2012, "C": 1972, "Java": 1995]
// return just the keys of languages
var result = languages.keys
print(result)
// Output: ["C", "Swift", "Java"]
keys Syntax
The syntax of the dictionary keys
property is:
dictionary.keys
Here, dictionary is an object of the Dictionary
class.
keys Return Values
The keys
property returns an array of all the keys of dictionary.
Example 1: Swift Dictionary keys
var information = ["Alcaraz": 18, "Sinner": 20, "Nadal": 34]
// keys total elements on names
print(information.keys)
Output
["Sinner", "Nadal", "Alcaraz"]
In the above example, we have used the keys
property to return an array of just the keys of the information dictionary.
Example 2: Using keys With for Loop
var informations = ["Alcaraz": 18, "Sinner": 20, "Nadal": 34]
// iterate through all the keys of informations
for information in informations.keys {
print(information)
}
Output
Nadal Alcaraz Sinner
Here, we have used the for
loop to iterate through all the keys of the informations dictionary.
Finally, all the keys of informations are printed one at a time.