Swift - Get to know Dictionaries

Introduction

A dictionary is a collection of objects of the same type that is identified using a key.

Consider the following example:

var myTable: Dictionary<String, String> = [
     "Apple": "iOS",
     "Google" : "Android",
     "Microsoft"  : "Windows Phone"
]

Here, myTable is a dictionary containing three items.

Each item is a key/value pair.

For example, "Apple" is the key that contains the value "iOS" .

The declaration specifies that the key and value must both be of the String type.

Due to type inference, you can shorten the declaration without specifying the Dictionary keyword and type specifications:

var myTable = [
     "Apple": "iOS",
     "Google" : "Android",
     "Microsoft" : "Windows Phone"
]

Unlike arrays, the ordering of items in a dictionary is not important.

This is because items are identified by their keys and not their positions.

The preceding could also be written like this:


var myTable = [
     "Microsoft" : "Windows Phone",
     "Google" : "Android",
     "Apple": "iOS"
]

The key of an item in a dictionary is not limited to String -it can be any of the hashable types.

The following example shows a dictionary using an integer as its key:

var ranking = [
     1: "Gold",
     2: "Silver",
     3: "Bronze"
]

The value of an item can itself be another array, as the following example shows:

var products = [
     "Apple" : ["iPhone", "iPad", "iPod touch"],
     "Google" :  ["Nexus S", "Nexus 4", "Nexus 5"],
     "Microsoft" : ["Lumia 920", "Lumia 1320","Lumia 1520"]
]

To access a particular product, first specify the key of the item you want to retrieve, followed by the index of the array:

Demo

var products = [
     "Apple" : ["iPhone", "iPad", "iPod touch"],
     "Google" :  ["Nexus S", "Nexus 4", "Nexus 5"],
     "Microsoft" : ["Lumia 920", "Lumia 1320","Lumia 1520"]
]

print(products["Apple"]![0])  //iPhone
print(products["Apple"]![1])  //iPad
print(products["Google"]![0]) //Nexus S

Result

You have to use the ! to force unwrap the value of the dictionary.

This is because the dictionary returns you an optional value.

It could potentially return you a nil value if you specify a key that does not exist, like this:

var models = products["Samsung"]   //models is nil

The safest way to extract values from a dictionary is to test for nil , like this:

Demo

var products = [
     "Apple" : ["iPhone", "iPad", "iPod touch"],
     "Google" :  ["Nexus S", "Nexus 4", "Nexus 5"],
     "Microsoft" : ["Lumia 920", "Lumia 1320","Lumia 1520"]
]

var models = products["Apple"]
if models != nil {
    print(models![0])   //iPhone
}

Result

Related Topic