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: 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: 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?
Avar dict = {String: Int}
Bvar dict = (String, Int)[]
Cvar dict = [String: Int]()
Dvar dict = [Int: String]()
✗ Incorrect
Option C correctly declares an empty dictionary with String keys and Int values.
What does this code do? dict["age"] = 30
ACreates a new dictionary
BDeletes the key "age"
CAccesses the value for key "age"
DAdds or updates the value 30 for the key "age"
✗ 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?
AAn optional of the value type
BThe value type directly
CA Boolean
DA String
✗ 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?
AUse optional binding with if let
BForce unwrap the value
CIgnore the value
DUse a for loop
✗ 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?
Avar dict = ("name" => "Alice", "age" => 25)
Bvar dict = ["name": "Alice", "age": 25]
Cvar dict = {"name": "Alice", "age": 25}
Dvar dict = ["name" -> "Alice", "age" -> 25]
✗ 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.
Practice
(1/5)
1. What is a dictionary in Swift used for?
easy
A. To store data in key-value pairs for quick lookup
B. To store a list of values without keys
C. To perform mathematical calculations
D. To create user interface elements
Solution
Step 1: Understand dictionary purpose
Dictionaries store data as pairs of keys and values, allowing fast access by key.
Step 2: Compare options
Only To store data in key-value pairs for quick lookup correctly describes this key-value storage purpose.
Final Answer:
To store data in key-value pairs for quick lookup -> Option A
Quick Check:
Dictionaries = key-value storage [OK]
Hint: Remember: dictionaries pair keys with values for fast access [OK]
Common Mistakes:
Confusing dictionaries with arrays (which have no keys)
Thinking dictionaries perform calculations
Assuming dictionaries create UI elements
2. Which of the following is the correct way to create a dictionary in Swift?
easy
A. let dict = ("apple", 1), ("banana", 2)
B. let dict = ["apple": 1, "banana": 2]
C. let dict = {"apple": 1, "banana": 2}
D. let dict = ["apple", 1, "banana", 2]
Solution
Step 1: Identify Swift dictionary syntax
Swift dictionaries use square brackets with key-value pairs separated by colons.
Step 2: Check each option
let dict = ["apple": 1, "banana": 2] uses correct syntax: ["key": value, ...]. Others use tuples, braces, or arrays incorrectly.
Final Answer:
let dict = ["apple": 1, "banana": 2] -> Option B
Quick Check:
Dictionary syntax = [key: value] [OK]
Hint: Use square brackets with colons for key-value pairs [OK]
Common Mistakes:
Using parentheses instead of square brackets
Using curly braces which define closures
Listing keys and values without colons
3. What will be the output of this Swift code?
let fruits = ["apple": 3, "banana": 5]
print(fruits["banana"] ?? 0)
medium
A. 5
B. nil
C. banana
D. 0
Solution
Step 1: Access dictionary value by key
fruits["banana"] looks up the value for key "banana", which is 5.
Step 2: Use nil-coalescing operator
The ?? 0 means if the key is missing (nil), print 0; here key exists, so print 5.
Final Answer:
5 -> Option A
Quick Check:
fruits["banana"] = 5 [OK]
Hint: Use ?? to provide default if key missing [OK]
Hint: Remember dictionary access returns optional, unwrap before use [OK]
Common Mistakes:
Thinking keys must be integers
Assuming dictionary is immutable by default
Ignoring optional nature of dictionary values
5. Given a dictionary let items = ["pen": 3, "notebook": 0, "eraser": 2], which Swift code correctly creates a new dictionary containing only items with quantity greater than zero?
hard
A. let filtered = items.compactMap { $0.value > 0 }
B. let filtered = items.filter { $0.key > 0 }
C. let filtered = items.filter { $0.value > 0 }
D. let filtered = items.map { $0.value > 0 }
Solution
Step 1: Understand filtering dictionary by value
We want to keep pairs where value > 0, so filter with condition on $0.value.
Step 2: Analyze each option
let filtered = items.filter { $0.value > 0 } uses filter with correct condition. let filtered = items.filter { $0.key > 0 } incorrectly compares key (a String) to 0. Options A and C use map/compactMap which transform values, not filter pairs.
Final Answer:
let filtered = items.filter { $0.value > 0 } -> Option C
Quick Check:
Filter dictionary by value > 0 = let filtered = items.filter { $0.value > 0 } [OK]
Hint: Use filter with $0.value condition to keep matching pairs [OK]
Common Mistakes:
Filtering by key instead of value
Using map instead of filter for selection
Using compactMap which changes type, not filters
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.