Complete the code to flatten the nested arrays into a single array.
let nested = [[1, 2], [3, 4], [5]] let flat = nested.[1] { $0 } print(flat)
The flatMap function flattens nested collections by applying a closure and then flattening the result. Here, it flattens the nested arrays into one array.
Complete the code to flatten and then double each number in the nested arrays.
let nested = [[1, 2], [3, 4], [5]] let doubled = nested.[1] { $0.map { $0 * 2 } } print(doubled)
flatMap is used here to flatten the nested arrays after doubling each element inside them.
Fix the error in the code to flatten the nested arrays correctly.
let nested = [[1, 2], [3, 4], [5]] let flat = nested.[1] { $0 } print(flat)
Using flatMap correctly flattens the nested arrays. Using map would keep the nested structure.
Fill both blanks to create a dictionary with words as keys and their lengths as values, only for words longer than 3 letters.
let words = ["apple", "bat", "car", "dolphin"] let lengths = Dictionary(uniqueKeysWithValues: words.filter { word in word.count > 3 }.map { word in ([1], [2]) })
The map closure uses word as the key and word.count as the value to create the dictionary for words longer than 3 letters.
Fill all three blanks to flatten a nested array of strings, convert each to uppercase, and filter only those starting with 'A'.
let nested = [["apple", "banana"], ["avocado", "berry"], ["apricot"]] let result = nested.[1] { $0.map { $0.[2]() }.filter { $0.hasPrefix([3]) } } print(result)
flatMap flattens the nested arrays, uppercased() converts strings to uppercase, and filtering with hasPrefix("A") keeps only strings starting with 'A'.