Dictionary in Swift

Sachinthana Weliwattage
3 min readJan 18, 2021

Dictionary is a common data type that stores data in the form of key-value pairs in the form of a table. Each entry has a “key” and a corresponding “value” and keys can be used to access the values in the dictionary.

In this article, I will be explaining the basic functions of dictionary in Swift and provide an example problem solved using dictionary data type.

Creating an empty Dictionary

This is the format to create an empty dictionary. You can simply use any dictionary name, KeyType and ValueType as you prefer.

var dictionaryName = [KeyType: ValueType]()

Example:

In the following example, an empty dictionary is created where the data type of the “keys” is Int and the data type of the values is String.

var dictionary = [Int: String]()

Creating Dictionary from a set of given values

Example:

Shown below are few examples where dictionaries are created with values.

var fruits:[Int:String] = [1:”Apple”, 2:”Orange”, 3:”Mango”, 4:”Grape”]var scores:[Int:Int] = [1:100, 2:200, 3:300, 4:400]var scores:[String:Int] = [“Score1”:400, “Score2”:2000, “Score3”:80, “Score4”:1600]var winners:[String:String] = [“1st Place”:”Adam”, “2nd Place”:”John”, “3rd Place”:”Nicky”]

Using Dictionary to count pairs in an array

In this example problem, assume you have an integer array. You are asked to count the number of matching pairs of elements.

For example, if you are given the following array of elements:

ar = [10, 10, 20, 20, 10, 10, 30, 50, 30, 20, 60, 60, 90]

The number of pairs will be 5 as shown below.

Let’s use Swift and dictionary data type to count the pairs.

First, let’s use a dictionary to count the occurrences of each value. At the end of this iteration (the first for loop in the code), the dictionary would have the following values.

Then, let’s use another for loop to iterate over the dictionary values.

We will count the pairs by dividing each value by 2. Since we are saving the values as Integers, dividing the value by 2 will give us the Integer value of pairs. (For example Integer 5 divided by 2 will give us 2, not 2.5)

The complete code is shown below:

func run(ar: [Int]) -> Int {    var counts :[Int:Int] = [Int:Int]()    for i in ar {        var iCount = counts[i]        if(iCount == nil){            iCount = 0        }        iCount! += 1        counts[i] = iCount    }    var pairCount = 0    for (_ , keyValue) in counts {        pairCount += (keyValue) / 2    }    return pairCount}print(run(ar: [10, 10, 20, 20, 10, 10, 30, 50, 30, 20, 60, 60, 90]))

Hope you learned the basic idea about what dictionary is and how to use it in swift.

Cheers!

--

--