0
0
Swiftprogramming~20 mins

FlatMap for nested collections in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
FlatMap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[1, 2, 3, 4, 5]
B[[1, 2], [3, 4], [5]]
C[[1], [2], [3], [4], [5]]
D[1, 2, [3, 4], 5]
Attempts:
2 left
💡 Hint
flatMap flattens one level of nested arrays into a single array.
Predict Output
intermediate
2: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)
A[1, 3, 4, nil]
B[1, nil, 3, 4, nil]
C[Optional(1), Optional(3), Optional(4)]
D[1, 3, 4]
Attempts:
2 left
💡 Hint
compactMap removes nil values while flatMap flattens the arrays.
🔧 Debug
advanced
2: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)
ATypeError: Cannot convert value of type '[[Int]]' to expected argument type '[Int]'
B[2, 4, 6, 8, 10]
C[[2, 4], [6, 8], [10]]
DRuntime error: Index out of range
Attempts:
2 left
💡 Hint
flatMap flattens after applying the map transformation.
📝 Syntax
advanced
2:00remaining
Syntax error in flatMap usage
Which option contains a syntax error when trying to flatten nested arrays with flatMap in Swift?
Alet flat = nested.flatMap { $0 }
Blet flat = nested.flatMap { $0.map { $0 * 2 } }
Clet flat = nested.flatMap { $0 * 2 }
Dlet flat = nested.flatMap { $0.flatMap { [$0] } }
Attempts:
2 left
💡 Hint
Inside flatMap closure, you must return a sequence, not a single value.
🚀 Application
expert
3: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"]
A
let uniqueCount = Set(sentences.flatMap { $0.split(separator: " ") }).count
print(uniqueCount)
B
let uniqueCount = Set(sentences.map { $0.split(separator: " ") }).count
print(uniqueCount)
C
let uniqueCount = sentences.flatMap { $0.split(separator: " ") }.count
print(uniqueCount)
D
let uniqueCount = sentences.map { $0.split(separator: " ") }.count
print(uniqueCount)
Attempts:
2 left
💡 Hint
flatMap flattens the arrays of words before creating a Set to count unique words.