Table of contents
1.
Introduction
2.
Create a dictionary in Swift
3.
Add Elements to a Dictionary
4.
Change Value of Dictionary
5.
Access Elements from Dictionary
6.
Remove an Element from a Dictionary
7.
Iterate Over a Dictionary
8.
Find Number of Dictionary Elements
9.
Create an Empty Dictionary
10.
Frequently Asked Questions
10.1.
What are the online websites for swift programming?
10.2.
What are the most important features of swift?
10.3.
What is init() in Swift?
10.4.
What are the control transfer statements that are used in iOS swift?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

Swift dictionary

Author SAURABH ANAND
0 upvote

Introduction

In this article, we will learn everything there is to know about Swift dictionary, including how they are constructed, how to access, add, and remove parts from them, and how to use various built-in functions

The swift dictionary is an unsorted list of items. It organizes elements into key/value pairs. Keys are unique identifiers associated with each value in this context.

Let's look at an example.

We may develop a dictionary using state names as keys and capitals as values to store information about countries and their capitals.

State Name

Capitals

Bihar Patna
Uttar Pradesh Lucknow
Jharkhand Ranchi

Create a dictionary in Swift

Here's how we create a dictionary in Swift.

var cap_city = ["Bihar": "Patna", "Uttar Pradesh": "Lucknow", "Jharkhand": "Ranchi"]
print(cap_city)

 

Output:

["Bihar": "Patna", "Uttar Pradesh": "Lucknow", "Jharkhand": "Ranchi"]

 

In this example, we created a dictionary called cap_city. Here,

  • Keys are "Bihar", "Uttar pradesh", "jharkhand"
  • Values are "patna", "uttar pradesh", "Ranchi"

 

When we execute this code, the output may be in a different sequence. This is due to the fact that the dictionary is not arranged in any specific order.

Add Elements to a Dictionary

We can add elements to a dictionary by prefixing the dictionary name with []. As an example,

var myDict:[String:Int] = ["sapna":75, "saurabh":82, "miller":79]
 
myDict["boult"] = 88
 
for (key, value) in myDict {
    print("\(key) : \(value)")
}

 

Output:

saurabh : 82
sapna : 75
miller : 79
boult : 88

 

Here, we have added a new element to cap_City with key: Jharkhand and value: Ranchi.

Change Value of Dictionary

We may also use [] to modify the value associated with a certain key. As an example,

var stu_ID = [101: "Saurabh", 102: "Gaurav", 103: "Anand"]
print("Initial Dictionary: ", stu_ID)
stu_ID[102] = "RamCharan"
print("Updated Dictionary: ", stu_ID)

 

Output:

Initial Dictionary:  [101: "Saurabh", 102: "Gaurav", 103: "Anand"]
Updated Dictionary: [101: "Saurabh", 102: "RamCharan", 103: "Anand"]

Access Elements from Dictionary

We can access the keys and values of a dictionary separately in Swift.

To access all of the keys in the dictionary, we use the keys property. As an example,

var cities = ["Bihar": "Patna", "Uttar Pradesh": "Lucknow", "Jharkhand": "Ranchi"]
print("Dictionary: ", cities)
var country_Name = Array(cities.keys)
print("Keys: ", country_Name)

 

Output:

Dictionary: ["Bihar": "Patna", "Uttar Pradesh": "Lucknow", "Jharkhand": "Ranchi"]
Keys:  ["Bihar", "Uttar Pradesh", "Jharkhand"]

Remove an Element from a Dictionary

To delete an element from the dictionary, we utilize the removeValue() method. As an example,

var stu_ID = [101: "Saurabh", 102: "RamCharan", 103: "Anand"]
print("Initial Dictionary: ", stu_ID)
var removedValue = stu_ID.removeValue(forKey: 102)
print("Dictionary After removeValue(): ", stu_ID)

 

Output:

Initial Dictionary: [101: "Saurabh", 102: "RamCharan", 103: "Anand"]
Dictionary After removeValue(): [101: "Saurabh", 103: "Anand"]

Iterate Over a Dictionary

The for loop is used to go over the elements of a dictionary. As an example,

var Names =  [101: "Saurabh", 102: "RamCharan", 103: "Anand"]
print("Keys: Values")
for (key,value) in Names {
  print("\(key): \(value)")
}


Output:

Keys: Values
101: Saurabh
102: RamCharan
103: Anand

Find Number of Dictionary Elements

The count property can be used to determine the number of elements in a dictionary. As an example,

var stu_ID = [101: "Saurabh", 102: "RamCharan", 103: "Anand"]
print(stu_ID.count)

 

Output:

3

Create an Empty Dictionary

We can also generate an empty dictionary in Swift. As an example,

var emptyDict =  [Int: String]()
print("Empty Dictionary: ",emptyDict)


Output:

Empty Dictionary:  [:]

 

In the above example, we have created an empty dictionary. Notice the expression

[Int: String]()

Here,

Int specifies that keys of the dictionary will be of integer type

String specifies that values of the dictionary will be of String type.

 

Note: When constructing an empty dictionary, you must define the data type of the dictionary.

Frequently Asked Questions

What are the online websites for swift programming?

Some of the available sites for online coding in swift language are Swiftstub.com, Runswiftlang.com, iswift.org, etc.

What are the most important features of swift?

Swift has the following significant features: More impressive structs and enums, Protocol oriented, Optional Types, etc.

What is init() in Swift?

The process of preparing an instance of an enumeration, structure, or class for use is known as initialization.

What are the control transfer statements that are used in iOS swift?

The following control transfer statements are used in iOS Swift:

Return, Break, Continue, and Fallthrough.

Conclusion

In this article, we have extensively discussed the concept of the Swift dictionary. We started with the introduction of Swift dictionary, creating Swift dictionary, adding elements in Swift dictionary, changing values in Swift dictionary, accessing elements in Swift dictionary, removing elements in Swift dictionary, and concluded with iterating over Swift dictionary.

 After reading about the swift dictionary, are you not feeling excited to read/explore more articles on the topic of file systems? Don't worry; Coding Ninjas has you covered. To learn, see  Swift Syntax and ProgramSwift continue and fallthrough statements, and Kotlin Architecture and Environment Setup

Also check out - Data Dictionary In Software Engineering

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your capacity in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio website. But if you have just started learning and are looking for questions asked by tech giants like Amazon, Microsoft, google, Uber, etc; you must look at the problemsinterview experiences, and interview bundle for placement preparations.

you may also consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass