in , ,

Swift Dictionary

Swift Dictionary
Swift Dictionary

Swift Dictionary: In this tutorial, you will learn about the dictionary is, creating a dictionary and some basic activities in dictionary.

In the previous Swift Arrays tutorial, we learned how we can store multiple values in a variable/constant. In this tutorial, we will talk about how we can store data/values as key value pairs.

In this article, you will learn-

What is a dictionary?

A dictionary is an unordered assortment of paired data, or key-value pairs.

A dictionary is essentially a container that can hold various data as key-value pair in an unordered manner.

Each worth is related with a unique key and stores data in unordered rundown as of Sets, for example you don’t get the elements in a similar order as you defined the items in the dictionary.

You may use dictionary rather than array when you need to look into value with some identifier in the assortment. Assume, you might need to look through the capital city of country. Around there, you will create a dictionary with key country and value capital city. Presently, you get the capital city from the assortment via looking with the key country.

In straightforward terms, you pair a key to a worth. In the above example, we paired a country to its capital city.


How to declare a dictionary in Swift?

You can create a vacant dictionary by indicating the key:value Data type inside square brackets[].

Example 1: Declaring an empty dictionary

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

At the point when you run the program, the output will be:

[:]

Or on the other hand

You can likewise define a vacant dictionary as underneath:

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

In the above program, we have declared a constant emptyDic of type dictionary with key of type Int and worth of type String and instated it with 0 values.

Or then again

Since, Swift is a sort reference language, you can likewise create dictionary straightforwardly without indicating the Data Type however should introduce for certain values so compiler can infer its sort as:


Example 2: Declaring an dictionary with some values

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

At the point when you run the program, the output will be:

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

In the above program, we have declared a dictionary without defining the sort expressly but instating with some default elements.

The element is in key:value pair where key is of type String and worth is of Int type. Since dictionary is an unordered rundown print(someDic)outputs the values in different order than defined.


Example 3: Creating dictionary from two arrays

We can likewise create a dictionary using arrays.

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

At the point when you run the program, the output will be:

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

In the above program,zip(customKeys,customValues) creates another Sequence of tuple with each element addressing value from customKeys and customValues. To learn more about how zip works, visit Swit zip.

Presently, we can pass this arrangement to the Dictionary(uniqueKeysWithValues:) initializer and create another Dictionary. Consequently, print(newDictionary) outputs another Dictionary with elements from two arrays.


How to access dictionary elements in Swift?

As arrays, you can access elements of a dictionary by using subscript syntax. You need to incorporate key of the worth you need to access inside square brackets immediately after the name of the dictionary.

Example 4: Accessing elements of a dictionary

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"])

At the point when you run the program, the output will be:

Optional(1)
Optional(8)

You can likewise get to elements of an dictionary using for-in loops.


Example 5: Accessing elements of an dictionary with for-in loop

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)")
}

At the point when you run the program, the output will be:

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 of in dictionary by using subscript syntax. You need to incorporate new key as the subscript index and assign another worth of the type as of Dictionary.

Example 6: Setting elements in a dictionary

var someDictionary = ["Pakistan":"Islamabad", "USA":"New York", "Turkey":"Istanbul"]
someDictionary["UK"] = "London"
print(someDictionary)

At the point when you run the program, the output will be:

["UK": "London", "USA": "New York", "Turkey": "Istanbul", "Pakistan": "Islamabad"]

In the above example, we’ve created another key-value pair “UK”: “London” in the given dictionary by using the subscript syntax.

You can likewise use subscript syntax to change the worth related with a specific key as:


Example 7: Changing elements of a dictionary

var someDictionary = ["Pakistan":"Islamabad", "USA":"New York", "Turkey":"Istanbul"]
someDictionary["Pakistan"] = "Islamabad"
print(someDictionary)

At the point when you run the program, the output will be:

["USA": "New York", "Turkey": "Istanbul", "Pakistan": "Islamabad"]

Some helpful built-in Dictionary functions & properties

1. isEmpty

This property decides whether a dictionary is unfilled or not. It returns true if a word reference doesn’t contain any worth in any case returns false.

Example 8: How isEmpty works?

let someDictionary = ["Pakistan":"Islamabad", "USA":"New York", "Turkey":"Istanbul"]
print(someDictionary.isEmpty)

At the point when you run the program, the output will be:

false

2. first

This property is used to get to the first element of a dictionary.

Example 9: How first works?

let someDictionary = ["Pakistan":"Islamabad", "USA":"New York", "Turkey":"Istanbul"]
print(someDictionary.first)

At the point when you run the program, the output will be:

Optional((key: "USA", value: "New York"))

3. count

This property returns the total number of element (key-value pair) in a dictionary.

Example 10: How count works?

let someDictionary = ["Pakistan":"Islamabad", "USA":"New York", "Turkey":"Istanbul"]
print(someDictionary.count)

At the point when you run the program, the output will be:

3

4. keys

This property returns every one of the keys inside the dictionary.

Example 11: How keys works?

var someDictionary = ["Pakistan":"Islamabad", "USA":"New York", "Turkey":"Istanbul"]
let dictKeys  = Array(someDictionary.keys)
print(dictKeys)

At the point when you run the program, the output will be:

["USA", "Turkey", "Pakistan"]

Also, you can use values to get every one of the values inside the dictionary.


5. removeValue

This function eliminates and returns the worth indicated with the key from the dictionary. Both key worth pair will be taken out from the dictionary.

Example 12: How removeValue() works?

var someDictionary = ["Pakistan":"Islamabad", "USA":"New York", "Turkey":"Istanbul"]
let val  = someDictionary.removeValue(forKey: "Pakistan")
print(val)
print(someDictionary)

At the point when you run the program, the output will be:

Optional("Kathmandu")
["Turkey": "Istanbul", "USA": "New York"]

Additionally, you can likewise utilize removeAll function to empty an dictionary.


Things to Remember

  1. While using subscript syntax to access elements of an dictionary in Swift, you should be certain the vital lies in the index else you will get a nil value. Let’s see this in example:

Example 13: Key must be present

var someDictionary = ["Pakistan":"Islamabad", "USA":"New York", "Turkey":"Istanbul"]
let val  = someDictionary["UK"]
print(val)

At the point when you run the program, the output will be:

nil

In the above program, there is no key UK. So when you attempt to get to the worth of the key “UK”, you will get a nil value.

  1. In like manner, key-values are case-sensitive in Swift, so you should ensure the correct cased key/value is used. Else, you will get a nil value. Let’s see this in example:

Example 14: Keys are case-sensitive

var someDictionary = ["Pakistan":"Islamabad", "USA":"New York", "Turkey":"Istanbul"]
let val  = someDictionary["Pakistan"]
print(val)

At the point when you run the program, the output will be:

nil

In the above program, there is no key Pakistan. So when you attempt to access the value of the key “Pakistan”, you will get a nil value.

  1. There is additionally an approach to give a default value if the value for a given key doesn’t exist. Let’s see this in example:

Example 12: Default value for non-existent key

var someDictionary = ["Pakistan":"Islamabad", "USA":"New York", "Turkey":"Istanbul"]
let val  = someDictionary["Pakistan", default:"Not Found"]
print(val)

At the point when you run the program, the output will be:

Not Found

In the above program, we have indicated a worth Not Found in the default parameter while getting to the dictionary. On the off chance that the worth doesn’t exist for the key, the default value is returned in any case the worth is returned.

For our situation, the key “Pakistan” is absent, so the program returns Not Found.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

Swift Sets

Swift Sets

Swift Functions

Swift Functions