0
0
Swiftprogramming~5 mins

Dictionary methods and default values in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A10
Bnil
CAn error
DThe old value for "a"
How do you provide a default value when accessing a dictionary key in Swift?
Adict.defaultValue(forKey: key)
Bdict.get(key, defaultValue)
Cdict[key] ?? defaultValue
Ddict[key, default: defaultValue]
What type does dict[key] return in Swift?
AOptional value
BAlways nil
CNon-optional value
DArray
Which method removes a key-value pair from a Swift dictionary?
Aremove(key:)
Bdelete(key:)
CremoveValue(forKey:)
Dpop(key:)
What happens if you assign a value to a new key in a Swift dictionary using subscript syntax?
AThe key-value pair is added
BThe dictionary throws an error
CNothing happens
DThe dictionary clears all entries
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.