Bird
Raised Fist0
Swiftprogramming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the flatMap function do when applied to a nested array in Swift?
easy
A. It flattens the nested arrays into a single array by combining all elements.
B. It sorts the nested arrays in ascending order.
C. It removes duplicate elements from the nested arrays.
D. It converts the nested arrays into a dictionary.

Solution

  1. Step 1: Understand the purpose of flatMap

    The flatMap function is designed to take a collection of collections and combine them into one single collection by flattening the nested structure.
  2. Step 2: Identify the effect on nested arrays

    When applied to nested arrays, flatMap merges all inner arrays into one continuous array containing all elements.
  3. Final Answer:

    It flattens the nested arrays into a single array by combining all elements. -> Option A
  4. Quick Check:

    flatMap flattens nested arrays = A [OK]
Hint: Remember: flatMap flattens nested arrays into one array [OK]
Common Mistakes:
  • Thinking flatMap sorts the array
  • Confusing flatMap with removing duplicates
  • Assuming flatMap converts arrays to dictionaries
2. Which of the following is the correct syntax to flatten a nested array let nested = [[1, 2], [3, 4]] using flatMap in Swift?
easy
A. let flat = nested.flatten()
B. let flat = nested.map { $0 }
C. let flat = nested.flatMap()
D. let flat = nested.flatMap { $0 }

Solution

  1. Step 1: Recall flatMap syntax

    The correct syntax for flattening nested arrays uses flatMap with a closure that returns each inner array: nested.flatMap { $0 }.
  2. Step 2: Evaluate each option

    let flat = nested.flatMap { $0 } uses the correct closure syntax. let flat = nested.map { $0 } uses map which does not flatten. let flat = nested.flatMap() is invalid syntax. let flat = nested.flatten() uses a non-existent method flatten().
  3. Final Answer:

    let flat = nested.flatMap { $0 } -> Option D
  4. Quick Check:

    flatMap with closure { $0 } flattens nested arrays [OK]
Hint: Use flatMap with closure { $0 } to flatten nested arrays [OK]
Common Mistakes:
  • Using map instead of flatMap
  • Calling flatMap without closure
  • Using non-existent flatten() method
3. What is the output of the following Swift code?
let nested = [[1, 2], [3, 4], [5]]
let result = nested.flatMap { $0.map { $0 * 2 } }
print(result)
medium
A. [1, 2, 3, 4, 5]
B. [2, 4, 6, 8, 10]
C. [[2, 4], [6, 8], [10]]
D. [1, 4, 9, 16, 25]

Solution

  1. Step 1: Understand the inner map operation

    Each inner array is mapped to a new array where each element is multiplied by 2, so [1,2] becomes [2,4], [3,4] becomes [6,8], and [5] becomes [10].
  2. Step 2: Apply flatMap to flatten the mapped arrays

    The flatMap then flattens these arrays into a single array: [2, 4, 6, 8, 10].
  3. Final Answer:

    [2, 4, 6, 8, 10] -> Option B
  4. Quick Check:

    flatMap + map doubles and flattens = [2,4,6,8,10] [OK]
Hint: flatMap flattens after map transforms inner elements [OK]
Common Mistakes:
  • Confusing flatMap with map output
  • Expecting nested arrays instead of flattened
  • Multiplying elements incorrectly
4. Identify the error in the following Swift code that attempts to flatten a nested array:
let nested = [["a", "b"], ["c"]]
let flat = nested.flatMap()
print(flat)
medium
A. flatMap requires a closure to specify how to flatten the nested arrays.
B. flatMap cannot be used on arrays of strings.
C. The variable 'flat' is immutable and cannot be assigned.
D. The print statement syntax is incorrect.

Solution

  1. Step 1: Check flatMap usage

    The flatMap function requires a closure to specify how to flatten the nested arrays, such as { $0 }. Calling flatMap() without arguments is invalid.
  2. Step 2: Verify other parts of the code

    Arrays of strings can be flattened with flatMap, variables can be assigned with let, and print syntax is correct.
  3. Final Answer:

    flatMap requires a closure to specify how to flatten the nested arrays. -> Option A
  4. Quick Check:

    flatMap needs closure { $0 } to flatten [OK]
Hint: Always provide closure { $0 } when using flatMap on nested arrays [OK]
Common Mistakes:
  • Calling flatMap without closure
  • Thinking flatMap can't flatten strings
  • Misunderstanding let variable assignment
  • Assuming print syntax is wrong
5. Given a nested array of optional integers let nested: [[Int?]] = [[1, nil], [3, 4], [nil]], which Swift code using flatMap correctly produces a flat array of non-nil integers?
hard
A. let flat = nested.flatMap { $0.filter { $0 != nil } }
B. let flat = nested.flatMap { $0.map { $0! } }
C. let flat = nested.flatMap { $0.compactMap { $0 } }
D. let flat = nested.flatMap { $0 }

Solution

  1. Step 1: Understand the data and goal

    The nested array contains optional integers, some are nil. The goal is to flatten and remove nil values, keeping only non-nil integers.
  2. Step 2: Analyze each option

    let flat = nested.flatMap { $0.compactMap { $0 } } uses compactMap inside flatMap to unwrap and remove nils, then flatten. let flat = nested.flatMap { $0.map { $0! } } force unwraps which can crash if nil exists. let flat = nested.flatMap { $0.filter { $0 != nil } } filters nil but keeps optionals, so result is nested optionals. let flat = nested.flatMap { $0 } just flattens but keeps nils.
  3. Final Answer:

    let flat = nested.flatMap { $0.compactMap { $0 } } -> Option C
  4. Quick Check:

    flatMap + compactMap unwraps and flattens non-nil values [OK]
Hint: Use compactMap inside flatMap to remove nils and flatten [OK]
Common Mistakes:
  • Force unwrapping optionals causing runtime errors
  • Filtering nil but not unwrapping optionals
  • Flattening without removing nil values
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard