Recall & Review
beginner
What is a dictionary in Swift?
A dictionary in Swift is a collection that stores key-value pairs. Each key is unique and is used to access its corresponding value.
Click to reveal answer
beginner
How do you create an empty dictionary in Swift?
You create an empty dictionary by specifying the key and value types inside square brackets, like this: <br>
var dict = [String: Int]()Click to reveal answer
beginner
How do you add or update a value in a Swift dictionary?
You assign a value to a key using subscript syntax: <br>
dict["key"] = value. If the key exists, the value updates; if not, it adds a new pair.Click to reveal answer
intermediate
How do you safely access a value from a Swift dictionary?
Use optional binding to check if the value exists: <br><code>if let value = dict["key"] { /* use value */ }</code>. This avoids errors if the key is missing.Click to reveal answer
beginner
What happens if you access a key that does not exist in a Swift dictionary?
Accessing a non-existent key returns nil because dictionary values are optional when accessed by key.
Click to reveal answer
How do you declare a dictionary with String keys and Int values in Swift?
✗ Incorrect
Option C correctly declares an empty dictionary with String keys and Int values.
What does this code do? <br>
dict["age"] = 30✗ Incorrect
Assigning a value to dict["age"] adds or updates the key-value pair.
What type is returned when you access a dictionary value by key in Swift?
✗ Incorrect
Accessing a dictionary by key returns an optional value because the key might not exist.
How can you safely use a value from a dictionary if the key might not exist?
✗ Incorrect
Optional binding lets you check if the value exists before using it safely.
Which of these is a correct way to create a dictionary with initial values?
✗ Incorrect
Option B uses correct Swift syntax for dictionary literals.
Explain how to create a dictionary in Swift and add a new key-value pair.
Think about how you declare types and assign values.
You got /3 concepts.
Describe how to safely access a value from a Swift dictionary and handle the case when the key does not exist.
Remember that dictionary lookups return optionals.
You got /3 concepts.