Challenge - 5 Problems
Swift Dictionary Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift dictionary access?
Consider the following Swift code. What will be printed?
Swift
let fruits = ["apple": 3, "banana": 5, "orange": 2] print(fruits["banana"] ?? 0)
Attempts:
2 left
💡 Hint
Remember that using ?? provides a default value if the key is missing.
✗ Incorrect
The dictionary fruits has a key "banana" with value 5. Accessing fruits["banana"] returns an Optional Int. Using ?? 0 unwraps it or returns 0 if nil. So the output is 5.
❓ Predict Output
intermediate2:00remaining
What does this dictionary creation code produce?
What is the content of the dictionary 'numbers' after this code runs?
Swift
let numbers = Dictionary(uniqueKeysWithValues: [(1, "one"), (2, "two"), (3, "three")]) print(numbers)
Attempts:
2 left
💡 Hint
Dictionary(uniqueKeysWithValues:) creates a dictionary from a sequence of key-value pairs.
✗ Incorrect
The code creates a dictionary with keys 1, 2, 3 and values "one", "two", "three" respectively. The print shows the dictionary in key:value pairs.
❓ Predict Output
advanced2:00remaining
What error does this Swift dictionary code raise?
What error will occur when running this code?
Swift
var dict = ["a": 1, "b": 2] let value = dict["c"]! print(value)
Attempts:
2 left
💡 Hint
Using ! to unwrap an Optional that is nil causes a runtime crash.
✗ Incorrect
Accessing dict["c"] returns nil because "c" is not a key. Using ! to force unwrap nil causes a runtime crash with the given error.
🧠 Conceptual
advanced2:00remaining
How many items are in the dictionary after this code?
After running this Swift code, how many key-value pairs does the dictionary 'items' contain?
Swift
var items = ["x": 10, "y": 20] items["z"] = 30 items["x"] = nil
Attempts:
2 left
💡 Hint
Setting a dictionary value to nil removes the key.
✗ Incorrect
Initially, items has 2 keys: "x" and "y". Adding "z" makes 3 keys. Setting "x" to nil removes it, leaving 2 keys: "y" and "z".
🔧 Debug
expert2:00remaining
What is the output of this Swift dictionary comprehension?
What will be printed by this Swift code?
Swift
let squares = Dictionary(uniqueKeysWithValues: (1...3).map { ($0, $0 * $0) }) print(squares[2] ?? -1)
Attempts:
2 left
💡 Hint
The dictionary maps numbers to their squares. Accessing key 2 returns 4.
✗ Incorrect
The dictionary squares has keys 1, 2, 3 with values 1, 4, 9. Accessing squares[2] returns Optional(4). Using ?? -1 unwraps it to 4.