Challenge - 5 Problems
FlatMap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of flatMap on nested arrays
What is the output of this Swift code using
flatMap on nested arrays?Swift
let nested = [[1, 2], [3, 4], [5]] let flat = nested.flatMap { $0 } print(flat)
Attempts:
2 left
💡 Hint
flatMap flattens one level of nested arrays into a single array.
✗ Incorrect
flatMap takes each inner array and combines their elements into one flat array. So [[1,2],[3,4],[5]] becomes [1,2,3,4,5].
❓ Predict Output
intermediate2:00remaining
flatMap with optional values in nested arrays
What is the output of this Swift code using
flatMap with optional values inside nested arrays?Swift
let nested: [[Int?]] = [[1, nil], [3, 4], [nil]] let flat = nested.flatMap { $0.compactMap { $0 } } print(flat)
Attempts:
2 left
💡 Hint
compactMap removes nil values while flatMap flattens the arrays.
✗ Incorrect
compactMap removes nils from each inner array, then flatMap merges all inner arrays into one array without nils.
🔧 Debug
advanced2:00remaining
Output of flatMap with map transformation
What is the output of this Swift code using
flatMap with map?Swift
let nested = [[1, 2], [3, 4], [5]] let flat = nested.flatMap { $0.map { $0 * 2 } } print(flat)
Attempts:
2 left
💡 Hint
flatMap flattens after applying the map transformation.
✗ Incorrect
flatMap applies the map to each inner array doubling values, then flattens the result into a single array.
📝 Syntax
advanced2:00remaining
Syntax error in flatMap usage
Which option contains a syntax error when trying to flatten nested arrays with flatMap in Swift?
Attempts:
2 left
💡 Hint
Inside flatMap closure, you must return a sequence, not a single value.
✗ Incorrect
Option C tries to multiply an array by 2 directly, which is invalid syntax in Swift.
🚀 Application
expert3:00remaining
Count unique words from nested sentences using flatMap
Given an array of sentences, which Swift code correctly uses flatMap to count the number of unique words across all sentences?
Swift
let sentences = ["hello world", "hello swift", "swift programming"]
Attempts:
2 left
💡 Hint
flatMap flattens the arrays of words before creating a Set to count unique words.
✗ Incorrect
Option A splits each sentence into words, flattens all words into one array, then creates a Set to count unique words.