Swift Dictionaries: A Complete Guide with Examples
In Swift, dictionaries are used to create collections of key-value pairs. In this tutorial, we will explore the basics of working with dictionaries in Swift.
Creating a Dictionary
To create a dictionary with key-value pairs, you can use the following syntax:
1 | var dict = ["Roger": 8, "Syd": 7] |
By default, the Swift compiler infers the type of the dictionary. However, you can also explicitly declare the type at the time of declaration:
1 | var dict: [String: Int] = ["Roger": 8, "Syd": 7] |
To create an empty dictionary, you can use either of the following syntax forms:
1 | var dict = [String: Int]() |
Accessing and Modifying Dictionary Values
To access a value assigned to a key in a dictionary, you can use the subscript syntax:
1 | var dict = ["Roger": 8, "Syd": 7] |
To change the value assigned to a key, you can simply assign a new value to the key:
1 | dict["Roger"] = 9 |
It’s important to note that the dictionary must be declared as var
(mutable) in order to modify it. If it’s declared with let
(immutable), you cannot add or remove elements.
To add a new key-value pair to a dictionary, use the same subscript syntax:
1 | dict["Tina"] = 4 |
To remove a key-value pair, you can assign nil
to the key or use the removeValue(forKey:)
method:
1 | dict["Tina"] = nil |
Dictionary Properties
To get the number of items in a dictionary, use the count
property:
1 | var dict = ["Roger": 8, "Syd": 7] |
If a dictionary is empty, its isEmpty
property will be true
:
1 | var dict = [String: Int]() |
Working with Dictionaries
Dictionaries are passed by value, which means if you pass a dictionary to a function or return it from a function, a copy of the dictionary is made.
Dictionaries can also be iterated over in loops, just like other collections in Swift.
Conclusion
In this tutorial, we learned how to create, access, and modify dictionaries in Swift. Dictionaries are a powerful data structure that allows you to store and retrieve values using unique keys. Understanding dictionaries is essential for building complex programs in Swift.
Tags: Swift, Dictionaries, Key-Value Pairs, Subscript Syntax, Properties