Sunday, July 7, 2019

Difference between swift map and flatMap

In swift, Array's map method has below signature
func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]

The flapMap method has the below signature
func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence

Both map and flatMap methods have a transform method to convert the original array element to a different array. In map, the transform takes a single element as input parameter and generate a single output element, then all output elements are appended in an array.

In flatMap, the transform method takes a single element as input parameter, however, the output is an array of ouput element type, and then all return arrays from the transform method are appended together into a single array and returns to caller.

Samples from Swift Array document
let numbers = [1, 2, 3, 4]

let mapped = numbers.map { Array(repeating: $0, count: $0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

No comments:

Post a Comment