flatMap和map的区别

408 阅读1分钟

flatMap和map的区别

背景

map和flatmap,从字面意思或者官网介绍,可能会给一些人在理解上造成困扰,所以今天专门花时间来分析,现整理如下:

map 和 flatMap 都是 Swift 中用于处理集合类型(如数组)的高阶函数。

官方的解释

map:Returns an array containing the results of mapping the given closure over the sequence's elements.

mapmap 函数接受一个闭包作为参数,这个闭包将序列中的每个元素作为其参数,并返回一个转换后的值。然后 map 函数返回一个新的数组,其中包含转换后的元素。以下是一个使用 map 函数的例子:

let numbers = [1, 2, 3, 4, 5]
let squared = numbers.map { $0 * $0 } // 结果是 [1, 4, 9, 16, 25]

flatMap:Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

flatMapflatMap 函数接受一个转换闭包作为参数,这个闭包将序列中的每个元素作为其参数,并返回一个序列。然后 flatMap 函数将这些序列连接起来,返回一个新的数组。以下是一个使用 flatMap 函数的例子:

let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let flattened = nestedNumbers.flatMap { $0 } // 结果是 [1, 2, 3, 4, 5, 6, 7, 8, 9]

在上述代码中,map 函数返回一个包含可选值的数组,而 flatMap 函数则过滤掉了 nil 值,返回一个只包含非 nil 值的数组。

总的来说,map 和 flatMap 的主要区别在于 flatMap 能够处理嵌套集合,并且能够过滤掉 nil 值。