Swift 4 Tutorial : Dictionary

Dictionary in swift :

Dictionaries are Collection that store key-value paired items.The values are of same type and all items are stored without any order. You can access any item using its key. It is not required that the keys should be a number always. All the keys should be of the same type and unique. A dictionary can be variable or constant in swift. If you declare it using ‘let’ keyword, it will become immutable and if you declare it using ‘var’ keyword, it will be mutable. Immutable means you cannot change its content. Mutable means content can be changed.

Declaring a Dictionary :

Two different ways are available to declare a dictionary in swift. Full form and short hand form.

Full form :

You can declare a dictionary writing the name in full like Dictionary<Key, Value> , where ‘key’ is the type for dictionary key and ‘value’ is the type for dictionary value. Below line will declare a dictionary with key type ‘String’ and value type ‘String’

var mydict : Dictionary<String,String>

Short form :

Instead of writing the full ‘Dictionary’ name, we can also declare it like [Key: Value] . e.g., to create a Dictionary with key of type ‘String’ and value of type ‘Int’, use :

var mydict : Dictionary<String,Int>

Initialize a Dictionary in swift :

Initializing a dictionary is same as the above i.e. we can either use full form or short form to initialize. Below example will initialize three different empty dictionaries :

var dict1 : Dictionary<String,Int> = Dictionary<String,Int>()
var dict2 = Dictionary<String,Int>()
var dict3 = [String:Int]()

print (dict1.count)
print (dict2.count)
print (dict3.count)

Only we need to use parentheses for initialization. For ‘dict2’, we are not defining the type as ‘Dictionary<String,Int>’ , as swift has a type inference mechanism that can identify the type of a variable or constant from the type of data we are assigning to them.

Dictionary Literal :

We can initialize a dictionary using dictionary literal in swift. In dictionary literal, all key-value pairs are written as pair inside square brackets. Key-value pair is separated by colons. Example :

var dict1 = [1 : "Monday",2 : "Tuesday",3 : "Wednesday"]

print (dict1.count)

It will print 3. We can also initialize an empty dictionary using dictionary literal :

var dict1 : [String:Int] = [:]

print (dict1.count)

In this case, we need to specify the type of the dictionary.

Check if a dictionary is empty in swift and print the number of elements :

To check if a dictionary is empty, we can check isEmpty boolean flag. To get the number of elements of a swift dictionary, count public variable can be read. It returns the number of key-value paired available in the dictionary :

var dict1 = [1:"One", 2 :"Two" ,3 : "Three"]
var dict2 = [String:Int]()

if(dict1.isEmpty){
    print ("dict1 is empty")
}else{
    print ("dict1 elements count : \(dict1.count)")
}

if(dict2.isEmpty){
    print ("dict2 is empty")
}else{
    print ("dict2 elements count : \(dict2.count)")

Output :

dict1 elements count : 3
dict2 is empty

Accessing elements of a dictionary :

By using subscript syntax, we can access an element of a dictionary. e.g. to get value for key with name myKey of a dictionary myDictionary, we can use myDictionary[myKey]. Example :

import UIKit

var dict1 = [10 :"MonDay", 20 :"TuesDay" ,30 : "WednesDay"]

print ("Dictionary dict1 value with key 30 : \(dict1[30])")

var dict2 = ["First" : 1 , "Second" : 2 , "Third" : 3]

print ("Dictionary dict2 value with key \"Second\" : \(dict2["Second"])")

Output :

Dictionary dict1 value with key 30 : Optional("WednesDay")
Dictionary dict2 value with key "Second" : Optional(2)

Modify a value in Dictionary :

To update or modify a value in swift dictionary, we can use updateValue( value: Dictionary.Value, forKey key: Dictionary.Key)_ method. This method takes the ‘key’ and ‘value’ and updates the value for that specific ‘key’. This method returns the previous value for that key. Also, if no key is available, then it will add one new key to the dictionary. Example :

import UIKit

var dict1 = [10 :"MonDay", 20 :"TuesDay" ,30 : "WednesDay"]
print ("Dictionary dict1 value with key 30 : \(dict1[30])")

//update value
var oldValue = dict1.updateValue("ThrusDay", forKey: 30)
print ("Dictionary dict1 value with key 30 after update : \(dict1[30]) , previously it was \(oldValue)")

//key is not available , so add one new element
dict1.updateValue("Friday", forKey: 40)
print (dict1)

Output :

Dictionary dict1 value with key 30 : Optional("WednesDay")
Dictionary dict1 value with key 30 after update : Optional("ThrusDay") , previously it was Optional("WednesDay")
[10: "MonDay", 20: "TuesDay", 30: "ThrusDay", 40: "Friday"]

Adding a value :

We can add an element to a dictionary by using the ’=’ operator :

var dict1 = [10 :"MonDay", 20 :"TuesDay" ,30 : "WednesDay"]

dict1[40] = "Thrusday"

print (dict1)

It will print :

[10: "MonDay", 20: "TuesDay", 30: "WednesDay", 40: "Thrusday"]

If we will pass ‘30’ as the key, it will update the value for key ‘30’ :

var dict1 = [10 :"MonDay", 20 :"TuesDay" ,30 : "WednesDay"]

dict1[30] = "Thrusday"

print (dict1)

Output :

[20: "TuesDay", 30: "Thrusday", 10: "MonDay"]

Removing items :

Three different ways are available to remove key-value pairs from a dictionary.

  1. Remove by setting a value to nil
  2. Remove by using ‘remove()’ method. The parameter should be the index of the item you want to remove.
  3. Remove by ‘removeValue()’ method. Parameter is key for this method.
import UIKit

var dict1 = [10 :"MonDay", 20 :"TuesDay" ,30 : "WednesDay" , 40 : "ThrusDay"]

//removing by setting value to nil
dict1[30] = nil

print ("Dictionary after value at key 30 is set to nil \(dict1)")

//removing using index
if let index = dict1.index(forKey: 10){
    dict1.remove(at: index)
}

print ("Dictionary after element at index for key 10 is removed \(dict1)")

//removing using key
dict1.removeValue(forKey: 40)
print ("Dictionary after element for key 40 is removed \(dict1)")

Output :

Dictionary after value at key 30 is set to nil [10: "MonDay", 20: "TuesDay", 40: "ThrusDay"]
Dictionary after element at index for key 10 is removed [20: "TuesDay", 40: "ThrusDay"]
Dictionary after element for key 40 is removed [20: "TuesDay"]

We can also remove all key-value pairs by calling removeAll() method to a dictionary.

var dict1 = [10 :"MonDay", 20 :"TuesDay" ,30 : "WednesDay" , 40 : "ThrusDay"]

//removing all
dict1.removeAll()

print ("Dictionary after all elements are removed \(dict1)")

Output :

Dictionary after all elements are removed [:]

Iterating a swift Dictionary :

We can iterate through keys, values or both key-value pairs using ‘for-in’ loop. Below example explains all three steps :

var dict1 = [10 :"MonDay", 20 :"TuesDay" ,30 : "WednesDay" , 40 : "ThrusDay"]

for key in dict1.keys{
    print ("key for dict1 \(key)")
}

print ("")

for value in dict1.values{
    print ("value for dict1 \(value)")
}

print ("")

for (key,value) in dict1{
    print ("key \(key) : value \(value)")
}

Output :

key for dict1 10
key for dict1 20
key for dict1 30
key for dict1 40

value for dict1 MonDay
value for dict1 TuesDay
value for dict1 WednesDay
value for dict1 ThrusDay

key 10 : value MonDay
key 20 : value TuesDay
key 30 : value WednesDay
key 40 : value ThrusDay

Creating an array from a dictionary :

We can create one array with all keys or values as elements like below :

var dict1 = [10 :"MonDay", 20 :"TuesDay" ,30 : "WednesDay" , 40 : "ThrusDay"]

var keyArr = [Int](dict1.keys)
var valueArr = [String](dict1.values)

print ("keyArr \(keyArr)")
print ("valueArr \(valueArr)")

Output :

keyArr [10, 20, 30, 40]
valueArr ["MonDay", "TuesDay", "WednesDay", "ThrusDay"]