Dictionaries in Swift

Kishore Premkumar
4 min readApr 15, 2020

--

What is Dictionary?

Dictionaries use a unique identifier known as a key to store a value that later can be referenced and looked up through the same key. Unlike items in an array, items in a dictionary do not have a specified order. You can use a dictionary when you need to lookup values based on their identifiers.

How to declare Dictionaries in swift?

You can create an empty dictionary by specifying “key: value” Data inside square brackets [].

var dictionaryName: [dataTypeOfKey:dataTypeOfValue]= [:]

we can declare any datatype for key and value.

Example

var studentDetails: [String:string]

Another method to declare a dictionary

var StudentDetails: Dictionary<String,String> = [:]

In the above program, we have declared a dictionary variable studentDetails with key as String, and value as String. Here I declared String as my datatype, you can go with your own choice. A dictionary key can be either an integer or a string without a restriction, but it should be unique within a dictionary.

var dictionaryName: [Int:String]

Declaring a dictionary with some values

let studentDetails = [ "16eu106": "kisan",
"16eu107": "mithun",
"16eu108": "pradeep"
]
print(studentDetails)

In the above program, We have declared a dictionary without defining the type explicitly but initializing with some default elements.

let studentDetails: [String:String] = [ "16eu106": "kisan",
"16eu107": "mithun",
"16eu108": "pradeep"
]
print(studentDetails)

In the above program, We have declared a dictionary with defining the type explicitly with some default elements.

Output

["16eu107": "mithun","16eu108": "pradeep","16eu106": "kisan"]

Since the dictionary is an unordered list printing the dictionary outputs the values in a different order than defined.

Creating a dictionary from two arrays

The syntax for creating a dictionary from two arrays

Dictionary(uniqueKeyWithValues: zip(array1,array2))

Example

let studentKeyArray = [1,2,3,4]
let studentValueArray = ["vasu","madhu","raniya","muthu"]
let studentDetailsDictionary = Dictionary(uniqueKeysWithValues: zip(studentKeyArray,studentValueArray))
print(studentDetailsDictionary)

Output

[1: "vasu", 2: "madhu", 3: "raniya", 4: "muthu"]

In the above program zip(studentKeyArray,studentValueArray) creates a new sequence with each element representing value from studentKeyArrayand studentValueArray. To learn more about how zip works, click.

We can pass this sequence to the Dictionary(uniqueKeysWithValues)initializer and create a new studentDetails Dictionary.

Adding elements in a dictionary

var studentDetails = [ 1 : "vasu",
2 : "madhu",
3 : "raniya",
]
studentDetails[4] = "Mishaa"

Note that the new key should not exist in the dictionary else it will be replaced. The value does not have any constraints.

In the above example, we’ve created a new key:value pair 4 : Mishaa in the given dictionary.

Output

[3: "raniya", 4: "Mishaa", 1: "vasu", 2: madhu]

Changing the elements of a dictionary

When you change the elements of a dictionary, make sure the key lies in the index otherwise it will be added as a new key and value.

var cricketPlayers = [ 7 : "Dhoni",                      
18 : "kohil",
10 : "aswin"
]
cricketPlayers[10] = "Sachin"
print(cricketPlayers)

Output

[10: "Sachin", 18: "kohil", 7: "Dhoni"]

Access elements of a dictionary

Syntax to access the elements of the dictionary.dictionaryName[key]

Example

var studentDetails = [ 1 : "vasu",                        
2 : "madhu",
3 : "raniya"
]
print(studentDetails[1])

Output

Optional("vasu")

We are accessing the value vasu with key 1

Unwrap the values safely

print(studentDetails[1] ?? "")

Output

vasu

Using optionals to unwrap the values safely. In above program I used nil coalescing operator.To learn more about how optionals works click.

Accessing an element of a dictionary with loop

var studentDetails = [ 1 : "vasu",                       
2 : "madhu",
3 : "raniya"
]
for (keys,values) in studentDetails {
print("key is \(keys). value is \(values) ")
}

output

keys : 2 , values : "madhu"
keys : 1 , values : "vasu"
keys : 3 , values : "raniya"

Keys stands for the key of the dictionary, Values stand for the value of the dictionary.

Nested dictionary

A nested dictionary is a dictionary inside a dictionary. I t’s a collection of dictionaries into one single dictionary.

let studentDetails = [["name": "vasu","age": 16,"totalMark": 420],["name": "kishore","age": 16,"totalMark": 380]]print(studentDetails[1])

Output

["name": "kishore", "totalMark": 380, "age": 16]

We can access the nested dictionary with their index value.

Merge two dictionary

1)Keep the current value (value in dictionary1) if there is a duplicate key

dictionary1.merge(dictionary2){(current, _) in current}

2)Keep the new value (value in dictionary2) if there is a duplicate key

dictionary1.merge(dictionary2){(_, new) in new}

Example

var iosDeveloper = [1: "balaji",                     
2: "karthi",
3: "vinoth",
4: "dhayalan"
]
var iosIntern = [5: "sritharan",
6: "kishore",
7: "sunitha",
8: "tony"
]
iosDeveloper.merge(iosIntern){(new,_) in new}
print(iosDeveloper)

Output

[5: "sritharan", 2: "karthi", 4: "dhayalan", 3: "vinoth", 8: "tony", 1: "balaji", 7: "sunitha", 6: "kishore"]

Length of a dictionary

Count property returns the total number of elements(key-value pairs) of a dictionary.

var studentDetails = [ 1 : "vasu",                        
2 : "madhu",
3 : "raniya"
]
print(studentDetails.count)

Output

3

Things to remember

1) You need to include key of the value you want to access within square brackets immediately after the name of the dictionary.
2) Likewise,key-value is case-sensitive in swift,so if you make a mistake nil value will be returned.
3) There is also a way to provide a default value if the given key does not exist.

Example:

let studentDetails = [ "CS1" : "kishore","CS2" : "Tony","CS3" : "dhayalan"]print(studentDetails["cs2", default: "Not Found"])//case sensitive

Output:

Not Found

In the above program, the specified key is not found in the dictionary. So, the default statement is executed.

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live” — Martin Golding

Find it a good read?

Recommend this post (by clicking 👏 button) so other people can see it too…
reach me on Twitter

--

--