Challenge - 5 Problems
Swift Collections Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
What is the output of this Swift code snippet?
Consider this Swift code that uses a dictionary to count occurrences of words. What will be printed?
iOS Swift
let words = ["apple", "banana", "apple", "orange", "banana", "apple"] var counts = [String: Int]() for word in words { counts[word, default: 0] += 1 } print(counts["apple"] ?? 0)
Attempts:
2 left
💡 Hint
Count how many times "apple" appears in the array.
✗ Incorrect
The code counts each word's occurrences. "apple" appears 3 times, so counts["apple"] is 3.
📝 Syntax
intermediate2:00remaining
Which option correctly creates a Set of unique integers in Swift?
You want to create a Set containing the numbers 1, 2, 3, 3, 4. Which code snippet does this correctly?
Attempts:
2 left
💡 Hint
Sets can be created from arrays using the Set initializer.
✗ Incorrect
Option A uses the Set initializer with an array, correctly creating a Set with unique values.
🧠 Conceptual
advanced2:00remaining
What happens when you access a dictionary key that does not exist in Swift?
Given a dictionary let dict = ["a": 1, "b": 2], what is the result of dict["c"]?
Attempts:
2 left
💡 Hint
Think about optional values in Swift.
✗ Incorrect
Accessing a non-existent key returns nil because dictionary lookups return optional values.
❓ lifecycle
advanced2:00remaining
What is the effect of modifying an Array while iterating over it in Swift?
Consider this code:
var numbers = [1, 2, 3]
for number in numbers {
numbers.append(number + 3)
}
What happens when this runs?
iOS Swift
var numbers = [1, 2, 3] for number in numbers { numbers.append(number + 3) }
Attempts:
2 left
💡 Hint
Think about how the for-in loop works with arrays.
✗ Incorrect
Appending elements during iteration extends the array, so the loop never ends, causing an infinite loop.
🔧 Debug
expert2:00remaining
Why does this Swift code cause a crash?
Examine this code:
var dict = ["key1": "value1"]
let value = dict["key2"]!
print(value)
Why does it crash?
iOS Swift
var dict = ["key1": "value1"] let value = dict["key2"]! print(value)
Attempts:
2 left
💡 Hint
Force unwrapping nil causes a crash.
✗ Incorrect
Accessing a missing key returns nil. Using ! to force unwrap nil causes a runtime crash.