Swift:Map,FlatMap,Filter,Reduce 理解

原文链接

Swift是支持一门函数式编程的语言,拥有Map,FlatMap,Filter,Reduce针对集合类型的操作.本文主要根据官方文档举例了解Swift中的Map,FlatMap,Filter,Reduce

Map

首先我们来看一下mapSwift中的的定义,我们看到它可以用在 Optionals 和 SequenceType 上(如:数组、词典等)

public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible {
    /// If `self == nil`, returns `nil`.  Otherwise, returns `f(self!)`.
    @warn_unused_result
    public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?
}

extension CollectionType {
    /// Returns an `Array` containing the results of mapping `transform`
    /// over `self`.
    ///
    /// - Complexity: O(N).
    @warn_unused_result
    public func map<T>(@noescape transform: (Self.Generator.Element) throws -> T) rethrows -> [T]
}

1869329-e17438ddf8171bbf.png

我们可以用For-in完成类似的操作

var values = [1,3,5,7]
var results = [Int]()
for var value in values {
    value *= 2
    results.append(value)
}
//"[2, 6, 10, 14]"
print(results)

Map操作

var values = [1,3,5,7]
let results = values.map (){ $0 * 2 }
//"[2, 6, 10, 14]"
相比较而言,代码精简了很多。可以理解为 map是直接对当前的数组进行处理,返回的还是当前的数组样式
FlatMap

与map一样,它可以用在 Optionals和 SequenceType 上(如:数组、词典等)。

public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible {
    /// Returns `nil` if `self` is `nil`, `f(self!)` otherwise.
    @warn_unused_result
    public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?
}

extension SequenceType {
    /// 返回一个将变换结果连接起来的数组
    /// `transform` over `self`.
    ///     s.flatMap(transform)
    /// is equivalent to
    ///     Array(s.map(transform).flatten())
    @warn_unused_result
    public func flatMap<S : SequenceType>(transform: (Self.Generator.Element) throws -> S) rethrows -> [S.Generator.Element]
}

extension SequenceType {
    /// 返回一个包含非空值的映射变换结果
    @warn_unused_result
    public func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]
}

一:空值过滤


var values:[Int?] = [1,3,5,7,9,nil]
let flattenResult = values.flatMap{ $0 }
/// [1, 3, 5, 7, 9]

二:压平,(降维)

var values = [[1,3,5,7],[9]]
let flattenResult = values.flatMap{ $0 }
/// [1, 3, 5, 7, 9]
FlatMap可以理解为强制空值过滤,剔除空值。强制压平\强制降维。
Filter

同样,我先来看看Swift中的定义:

extension SequenceType {
    /// 返回包含原数组中符合条件的元素的数组
    /// Returns an `Array` containing the elements of `self`,
    /// in order, that satisfy the predicate `includeElement`.
    @warn_unused_result
    public func filter(@noescape includeElement: (Self.Generator.Element) throws -> Bool) rethrows -> [Self.Generator.Element]
}

eg: 我们向flatMap传入了一个闭包,筛选出了能被3整除的数据

var values = [1,3,5,7,9]
let flattenResults = values.filter{ $0 % 3 == 0}
//[3, 9]
Filter 可以理解为条件过滤,返回包含原数组中符合条件的元素的数组
Reduce

我们先来看下Swift中的定义:

extension SequenceType {
    /// Returns the result of repeatedly calling `combine` with an
    /// accumulated value initialized to `initial` and each element of
    /// `self`, in turn, i.e. return
    /// `combine(combine(...combine(combine(initial, self[0]),
    /// self[1]),...self[count-2]), self[count-1])`.
    @warn_unused_result
    public func reduce<T>(initial: T, @noescape combine: (T, Self.Generator.Element) throws -> T) rethrows -> T
}

eg

let fiveArray = [1,2,3,4,5]
let sum = fiveArray.reduce(0) { $0 + $1 } //求数组元素的和
let sum1 = fiveArray.reduce(0, +) // 简写
let sum2 = fiveArray.filter{ $0 > 2 }.reduce(0, +)  // 数组中元素大于2 的数据求和
print(sum,sum1,sum2)
// 15 15 12
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swift 中,`map` 和 `flatMap` 是两个常用的高阶函数,用于处理数组(Array)或可选值(Optional)。 1. `map` 函数:`map` 函数可以将一个数组中的每个元素都应用一个转换函数,并返回一个新的数组,新数组的元素是原数组经过转换后的结果。例如: ```swift let numbers = [1, 2, 3, 4, 5] let doubledNumbers = numbers.map { $0 * 2 } print(doubledNumbers) // 输出 [2, 4, 6, 8, 10] ``` 在上面的例子中,`map` 函数将数组 `numbers` 中的每个元素都乘以 2,返回了一个新的数组 `doubledNumbers`。 2. `flatMap` 函数:`flatMap` 函数可以将一个数组中的每个元素都应用一个转换函数,然后将转换结果连接起来,并返回一个新的数组。与 `map` 不同的是,`flatMap` 还会自动过滤掉转换结果中的 `nil` 值(如果有的话)。例如: ```swift let names = ["Alice", "Bob", "Charlie"] let flattenedNames = names.flatMap { $0.uppercased() } print(flattenedNames) // 输出 ["A", "L", "I", "C", "E", "B", "O", "B", "C", "H", "A", "R", "L", "I", "E"] ``` 在上面的例子中,`flatMap` 函数将数组 `names` 中的每个元素都转换成大写字母,并将结果连接起来,得到了一个新的数组 `flattenedNames`。 需要注意的是,对于可选值(Optional),`flatMap` 函数还有另外一种用法。它可以将一个可选值进行解包,并返回其中的非空值,如果可选值为 `nil`,则返回一个空的数组。例如: ```swift let optionalNumber: Int? = 5 let flattenedNumber = optionalNumber.flatMap { [$0 * 2] } print(flattenedNumber) // 输出 [10] let nilOptionalNumber: Int? = nil let flattenedNilNumber = nilOptionalNumber.flatMap { [$0 * 2] } print(flattenedNilNumber) // 输出 [] ``` 在上面的例子中,`flatMap` 函数将可选值 `optionalNumber` 解包,并将解包后的非空值乘以 2,并返回一个包含该结果的数组。而对于 `nilOptionalNumber`,由于可选值为 `nil`,所以返回了一个空的数组。 希望这些示例能够帮助你理解 Swift 中 `map` 和 `flatMap` 的用法。如果你还有其他问题,请随时提问!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值