0
0
Swiftprogramming~10 mins

FlatMap for nested collections in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to flatten the nested arrays into a single array.

Swift
let nested = [[1, 2], [3, 4], [5]]
let flat = nested.[1] { $0 }
print(flat)
Drag options to blanks, or click blank then click option'
Amap
BflatMap
Cfilter
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of flatMap results in a nested array.
Using filter or reduce does not flatten the array.
2fill in blank
medium

Complete the code to flatten and then double each number in the nested arrays.

Swift
let nested = [[1, 2], [3, 4], [5]]
let doubled = nested.[1] { $0.map { $0 * 2 } }
print(doubled)
Drag options to blanks, or click blank then click option'
AflatMap
Breduce
Cfilter
Dmap
Attempts:
3 left
💡 Hint
Common Mistakes
Using map only results in a nested array of doubled numbers.
Using filter or reduce does not flatten the array.
3fill in blank
hard

Fix the error in the code to flatten the nested arrays correctly.

Swift
let nested = [[1, 2], [3, 4], [5]]
let flat = nested.[1] { $0 }
print(flat)
Drag options to blanks, or click blank then click option'
Afilter
Bmap
CflatMap
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of flatMap causes nested arrays in the output.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their lengths as values, only for words longer than 3 letters.

Swift
let words = ["apple", "bat", "car", "dolphin"]
let lengths = Dictionary(uniqueKeysWithValues: words.filter { word in word.count > 3 }.map { word in ([1], [2]) })
Drag options to blanks, or click blank then click option'
Aword
Bword.count
Clen(word)
Dword.length
Attempts:
3 left
💡 Hint
Common Mistakes
Using Python syntax like len(word) instead of Swift's word.count.
Using word.length which is not valid in Swift.
5fill in blank
hard

Fill all three blanks to flatten a nested array of strings, convert each to uppercase, and filter only those starting with 'A'.

Swift
let nested = [["apple", "banana"], ["avocado", "berry"], ["apricot"]]
let result = nested.[1] { $0.map { $0.[2]() }.filter { $0.hasPrefix([3]) } }
print(result)
Drag options to blanks, or click blank then click option'
AflatMap
Bmap
C"A"
Duppercased
Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of flatMap causes nested arrays in the result.
Using lowercase 'a' in hasPrefix causes no matches.
Forgetting to call uppercased() as a method.