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 code using dictionary default values?
Consider the following Swift code. What will be printed when it runs?
Swift
var scores = ["Alice": 10, "Bob": 5] scores["Charlie", default: 0] += 3 print(scores)
Attempts:
2 left
💡 Hint
Look at how the default value is used to add or update the dictionary entry.
✗ Incorrect
Using the default value 0 for key "Charlie", the code adds 3 to it, creating a new entry with value 3.
❓ Predict Output
intermediate2:00remaining
What does this Swift code print when using the removeValue method?
Given this Swift code, what will be printed?
Swift
var fruits = ["apple": 3, "banana": 2, "orange": 5] let removed = fruits.removeValue(forKey: "banana") print(removed ?? "none") print(fruits)
Attempts:
2 left
💡 Hint
removeValue returns the removed value or nil if key not found.
✗ Incorrect
The key "banana" exists with value 2, so removeValue returns 2 and removes the key from the dictionary.
🔧 Debug
advanced2:00remaining
Why does this Swift code cause a runtime error?
Examine this Swift code snippet. Why does it crash at runtime?
Swift
var dict = ["x": 1, "y": 2] let value = dict["z"]! print(value)
Attempts:
2 left
💡 Hint
Check what happens when you force unwrap a nil optional.
✗ Incorrect
Accessing a non-existent key returns nil. Force unwrapping nil causes a runtime crash.
🧠 Conceptual
advanced2:00remaining
How does the default value subscript work in Swift dictionaries?
Which statement best describes how the default value subscript works in Swift dictionaries?
Attempts:
2 left
💡 Hint
Think about whether the dictionary changes when using the default value subscript.
✗ Incorrect
The default value subscript inserts the default value if the key is missing, then returns it, allowing modification.
❓ Predict Output
expert3:00remaining
What is the final content of the dictionary after this Swift code runs?
Analyze the code below and determine the final dictionary content printed.
Swift
var inventory = ["pen": 3, "notebook": 5] inventory["pen", default: 0] += 2 inventory["eraser", default: 0] += 1 inventory["notebook", default: 0] -= 3 print(inventory)
Attempts:
2 left
💡 Hint
Remember the default value subscript inserts missing keys and allows arithmetic updates.
✗ Incorrect
The code adds 2 to "pen" (3+2=5), adds 1 to new key "eraser", and subtracts 3 from "notebook" (5-3=2).