Intern
What is your favorite function in the Swift language?
sobes.tech AI
Answer from AI
My favorite function is flatMap for collections.
It allows transforming a collection containing optional values or nested collections into a flat collection, discarding nil or merging nested elements.
Example with optionals:
// Array of strings, some of which may be nil
let strings: [String?] = ["Hello", nil, "World", nil, "Swift"]
// Use flatMap to remove nil and get an array of non-optional strings
let nonNilStrings = strings.flatMap { $0 }
// nonNilStrings is now ["Hello", "World", "Swift"]
Example with nested collections:
// Array of arrays of numbers
let nestedArrays = [[1, 2], [3, 4, 5], [6]]
// Use flatMap to create a single flat array
let flatArray = nestedArrays.flatMap { $0 }
// flatArray is now [1, 2, 3, 4, 5, 6]
flatMap makes code cleaner and more expressive when working with such data structures, eliminating the need to write bulky loops or use compactMap.