- Dictionary stores a list of key, value pairs of the same type in it.
- It does not have any order. Each iteration can result in different order of elements.
- A Dictionary is usually accessed using the key to get the associated value of it.
Declaring a Dictionary
Like Arrays there are several ways to declare a dictionary. Following examples show some different long form and short form ways to declare an empty Dictionary.
1
2
3
4
5
6
7
var studentsToScores: Dictionary<String, Int> = Dictionary<String, Int>()
var studentsToScores2 = Dictionary<String, Int>()
var studentsToScores3: [String: Int] = [String: Int]()
var studentsToScores4 = [String: Int]()
var studentsToScores5: [String: Int] = [:]
We can also declare a dictionary by directly assigning some key, value pairs and Swift will infer the key and value type
1
2
var studentToScores = ["John": 89, "Marry": 98, "Mark": 77]
print(studentToScores)
Output
1
["Marry": 98, "John": 89, "Mark": 77]
As you can see in the above output, it is not printing in the same order as we added the values to the dictionary.
Adding items into dictionary
We can just add new items or replace the value of already present keys by using subscripts
1
2
3
4
5
6
var studentToScores = ["John": 89, "Marry": 98, "Mark": 77]
print(studentToScores)
studentToScores["Kevin"] = 99
studentToScores["John"] = 80
print(studentToScores)
Output:
1
2
3
["John": 89, "Marry": 98, "Mark": 77]
["John": 80, "Kevin": 99, "Mark": 77, "Marry": 98]
Iterating over a Dictionary
We can easily iterate over all the keys and values of a dictionary and get all the values
1
2
3
for studentToScore in studentToScores {
print(key)
}
Output:
1
2
3
4
(key: "Marry", value: 98)
(key: "John", value: 80)
(key: "Kevin", value: 99)
(key: "Mark", value: 77)
We can also get keys and corresponding values individually while iterating in a Tuple
1
2
3
for (student, score) in studentToScores {
print("\(student) scored \(score)")
}
Output:
1
2
3
4
Kevin scored 99%
John scored 80%
Mark scored 77%
Marry scored 98%
Removing a value
We can either use removeValue(forKey: )
method or just assign nil
to the key using a subscript
1
2
3
studentToScores.removeValue(forKey: "John")
studentToScores["Mark"] = nil
print(studentToScores)
Output:
1
["Marry": 98, "Kevin": 99]
Accessing Keys
In certain situations we might need to just access the keys. Dictionaries provide a property that gives the list of keys
1
print(studentToScores.keys)
Output
1
["Marry", "Kevin"]