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:

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:

var dict: [String: Int] = ["Roger": 8, "Syd": 7]

To create an empty dictionary, you can use either of the following syntax forms:

var dict = [String: Int]()

//or

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:

var dict = ["Roger": 8, "Syd": 7]

dict["Roger"] // 8
dict["Syd"] // 7

To change the value assigned to a key, you can simply assign a new value to the key:

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:

dict["Tina"] = 4

To remove a key-value pair, you can assign nil to the key or use the removeValue(forKey:) method:

dict["Tina"] = nil

//or

dict.removeValue(forKey: "Tina")

Dictionary Properties

To get the number of items in a dictionary, use the count property:

var dict = ["Roger": 8, "Syd": 7]
dict.count // 2

If a dictionary is empty, its isEmpty property will be true:

var dict = [String: Int]()
dict.isEmpty // true

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