Recall & Review
beginner
What does the
updateValue(_:forKey:) method do in a Swift dictionary?It updates the value for the given key if it exists, or adds a new key-value pair if the key is not present. It returns the old value if it was replaced, or
nil if the key was new.Click to reveal answer
beginner
How can you safely access a value from a Swift dictionary with a default value if the key is missing?
Use the subscript with default value syntax:
dict[key, default: defaultValue]. This returns the value for the key if it exists, or the default value otherwise.Click to reveal answer
intermediate
What is the difference between
dict[key] and dict[key, default: defaultValue] in Swift?dict[key] returns an optional value that is nil if the key is missing. dict[key, default: defaultValue] returns a non-optional value, using the default if the key is missing.Click to reveal answer
beginner
How does the
removeValue(forKey:) method work in Swift dictionaries?It removes the key-value pair for the given key if it exists and returns the removed value. If the key is not found, it returns
nil.Click to reveal answer
beginner
What happens when you assign a value to a dictionary key using subscript syntax in Swift?
If the key exists, the value is updated. If the key does not exist, a new key-value pair is added to the dictionary.
Click to reveal answer
What does
dict.updateValue(10, forKey: "a") return if the key "a" was not in the dictionary?✗ Incorrect
It returns nil because there was no old value for the key "a" before the update.
How do you provide a default value when accessing a dictionary key in Swift?
✗ Incorrect
The correct syntax is dict[key, default: defaultValue]. Option C is valid Swift syntax but uses optional coalescing, not dictionary default subscript.
What type does
dict[key] return in Swift?✗ Incorrect
dict[key] returns an optional because the key might not exist in the dictionary.
Which method removes a key-value pair from a Swift dictionary?
✗ Incorrect
The correct method to remove a key-value pair is removeValue(forKey:).
What happens if you assign a value to a new key in a Swift dictionary using subscript syntax?
✗ Incorrect
Assigning a value to a new key adds that key-value pair to the dictionary.
Explain how to update a value in a Swift dictionary and how to handle the old value.
Think about the method that returns the previous value when you change a dictionary entry.
You got /3 concepts.
Describe how to access a dictionary value with a default fallback in Swift.
It's a special subscript syntax that avoids optionals.
You got /3 concepts.