Boring guide to Dictionaries in Swift

Jun 27, 20
  • 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.

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

var studentToScores = ["John": 89, "Marry": 98, "Mark": 77]


["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

var studentToScores = ["John": 89, "Marry": 98, "Mark": 77]

studentToScores["Kevin"] = 99
studentToScores["John"] = 80


["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

for studentToScore in studentToScores {


(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

for (student, score) in studentToScores {
    print("\(student) scored \(score)")


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

studentToScores.removeValue(forKey: "John")
studentToScores["Mark"] = nil


["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



["Marry", "Kevin"]