Swift-map()跟flatMap()区别
map()方法介绍
map() 是 Array 提供的方法,通过接收一个函数作为传入参数,对数组中每个元素进行函数变换得到新的结果值。这样只需要提供 X->Y 的映射关系,就能将数组 [X] 变换到新数组 [Y] ,而无需创建一个临时可变数组
var names:Array = ["Swift", "Arial", "Soga", "Donary"] func test1(person:String) -> String { return "hello \(person)" } let namesP = names.map(test1)
使用flatMap()
这个时候就轮到 flatMap() 来救场了。
flatMap() 与 map() 相似,但 flatMap() 用的是 T->U? 变换而不是 T->U 转化,而且倘若变换后的数组元素值为 nil 2 ,则不会被添加到最后的结果数组里面。
从语法上,你可以这么理解, flatMap 就是先使用 map 处理数组,接着将结果数组“压平”(顾名思义),也就是从输出数组里剔除值为 nil 的元素。
let nameP = names.flatMap(test1)

浙公网安备 33010602011771号