English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Dictionaries (Dictionary)

In this tutorial, you will learn what a dictionary is, how to create a dictionary, and some common operations in a dictionary.

In the previousSwift ArrayIn the article, we learned how to declare variables/Store multiple values in constants. In this article, we will discuss how to store data/Values are stored as key-value pairs.

What is a dictionary?

A dictionary is just a container that can store multiple data as key-value pairs in an unordered manner.

Each value is associated with a unique key and stores data in an unordered list asCollectionThat is to say, the order in which you obtain the elements is different from the order in which you define the items in the dictionary.

When you need to find a value with a specific identifier in a collection, you can use a dictionary instead of an array. Suppose you want to search for the capital of this country. In this case, you will create a dictionary with the country and capital city as key-value pairs. Now, you can obtain the value: capital by searching for the key: country from the collection.

In simple terms, you pair keys with values. In the above example, we pair a country with its capital.

How to declare a dictionary in Swift?

You can create an empty dictionary by specifying key: value data type within square brackets[].

Example1Declaring an empty dictionary

let emptyDic:[Int:String] = [:]
print(emptyDic)

When running the program, the output is:

[:]
Or

You can also define an empty dictionary as follows:

let emptyDic:Dictionary<Int, String> = [:]
print(emptyDic)

In the above program, we declared a constant emptyDic of type dictionary with Int-type keys and String-type values, and initialized it with a 0 value.

Or

Since Swift is a type inference language, you can also create a dictionary without specifying the data type, but you must initialize it with some values so that the compiler can infer it as:

Example2Declaring a dictionary with certain values

let someDic = ["a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9]
print(someDic)

When running the program, the output is:

["b": 2, "a": 1, "i": 9, "c": 3, "e": 5, "f": 6, "g": 7, "d": 4, "h": 8]

In the above program, we declared a dictionary but did not explicitly define the type, instead initializing it with some default elements.

Elements are located in key:value pairs, where the key type is String and the value type is Int. Since dictionaries are unordered lists, print(someDic) outputs values in an order different from the defined order.

Example3Creating a dictionary from two arrays

We can also use an array to create a dictionary.

let customKeys = ["Facebook", "Google", "Amazon"]
let customValues = ["Mark", "Larry", "Jeff"]
let newDictionary = Dictionary(uniqueKeysWithValues: zip(customKeys,customValues))
print(newDictionary)

When running the program, the output is:

["Amazon": "Jeff", "Google": "Larry", "Facebook": "Mark"]

In the above program, zip(customKeys,customValues) creates a new tuple sequence, each element representing values from customKeys and customValues.

Now, we can pass this sequence to the Dictionary(initialValue: Dictionary(uniqueKeysWithValues:)) initializer and create a new Dictionary. Therefore, print(NewDictionary) outputs a new Dictionary containing elements from both arrays.

How to access dictionary elements in Swift?

As an array, you can use index syntax to access dictionary elements. You need to include the key of the value you want to access in the brackets after the dictionary name.

Example4To access dictionary elements

let someDic = ["a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9]
print(someDic["a"])
print(someDic["h"])

When running the program, the output is:

Optional(1)
Optional(8)

You can also use for-in loop to access dictionary elements.

Example5Using for-in loop to access dictionary elements

let someDic = ["a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9]
for (key,value) in someDic {
    print("key:\(key) value:\(value)")
}

When running the program, the output is:

key:b value:2
key:a value:1
key:i value:9
key:c value:3
key:e value:5
key:f value:6
key:g value:7

How to modify dictionary elements in Swift?

You can add elements to the dictionary using index syntax. You need to include New key As an index and assign a new value to the Dictionary type.

Example6To set an element in the dictionary

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
someDictionary["Japan"] = "Tokyo"
print(someDictionary)

When running the program, the output is:

["Japan": "Tokyo", "China": "Beijing", "India": "NewDelhi", "Nepal": "Kathmandu"]

In the above example, we used index syntax to create a new key-value pair "Japan": "Tokyo" in the given dictionary.

You can also use index syntax to change the value associated with a specific key:

Example7To change the element of the dictionary

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
someDictionary["Nepal"] = "KATHMANDU"
print(someDictionary)

When running the program, the output is:

["China": "Beijing", "India": "NewDelhi", "Nepal": "KATHMANDU"]

Built-in functions and properties of dictionaries

1.isEmpty property - Judge whether the dictionary is empty

This property determines whether the dictionary is empty. If the dictionary does not contain any values, it returns true, otherwise it returns false.

Example8How does isEmpty work?

let someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
print(someDictionary.isEmpty)

When running the program, the output is:

false

2.first property - Returns the first element of the dictionary

This property is used to access the first element of the dictionary.

Example9: How does first work?

let someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
print(someDictionary.first)

When running the program, the output is:

Optional((key: "China", value: "Beijing"))

3.count - Returns the total number of dictionary elements

This property returns the total number of elements (key-value pairs) in the dictionary.

Example10: How does count work?

let someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
print(someDictionary.count)

When running the program, the output is:

3

4.keys property - Returns all the keys in the dictionary

This property returns all the keys in the dictionary.

Example11: How does keys work?

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
let dictKeys = Array(someDictionary.keys)
print(dictKeys)

When running the program, the output is:

["China", "India", "Nepal"]

Similarly, you can use  values property to get all the values in the dictionary.

5. removeValue

This function is used to delete and return the value specified by the key from the dictionary. Both of these key-value pairs will be removed from the dictionary.

Example12: How does removeValue() work?

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
let val = someDictionary.removeValue(forKey: "Nepal")
print(val)
print(someDictionary)

When running the program, the output is:

Optional("Kathmandu")
["India": "NewDelhi", "China": "Beijing"]

Similarly, you can also use removeAll The function clears the dictionary.

Notes

1.When accessing elements in a dictionary using the subscript syntax in Swift, you must ensure that the key is located in the index, otherwise you will getnilValue. Let's see an example:

Example13: The key must exist

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
let val = someDictionary["Japan"]
print(val)

When running the program, the output is:

nil

In the above program, there is no key Japan . Therefore, when you try to access the key "Japan when you access it, you will get a nil value.

2.Similarly, keys are case-sensitive in Swift, so you must ensure that you use the correct case for the key/Value. Otherwise, you will get a nil value. Let's see an example:

Example14: Key is case-sensitive

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
let val = someDictionary["nepal"]
print(val)

When running the program, the output is:

nil

In the above program, there is no key 'nepal'. Therefore, when you try to access the key 'nepal', you will get a nil value.

3.If the value of the given key does not exist, there is also another way to provide a default value. Let's see an example in the following demonstration:

Example12: Default value for non-existing key

var someDictionary = ["Nepal":"Kathmandu", "China":"Beijing", "India":"NewDelhi"]
let val  = someDictionary["nepal", default:"Not Found"]
print(val)

When running the program, the output is:

Not Found

In the above program, we specified a default value in the default parameter when accessing the dictionary. If the value of the key does not exist, the default value is returned, otherwise the value is returned

In our example, the key"nepal"Not found, therefore the program returns the default value: Not Found.