iOneWay Blog

天道地道,自求我道

QQ:373850874. 欢迎加入。


Swift中的map, filter, reduce 函数

Swift中Array支持三个高阶函数,map, filter和reduce。对于我们对数组进行操作带来了很大的方便。

高阶函数的定义:满足以下两点其一即为高阶函数:1,接受一个或者多个函数作为输入;2,输出一个函数。

map函数

map函数的作用:对某一个数组中的元素进行转换,然后产生一个新的数组。
map函数是CollectionType协议中定义的方法:
public func map<T>(@noescape transform: (Self.Generator.Element) throws -> T) rethrows -> [T]

该定义是一个泛型定义。

@noescape:用于解除闭包的循环引用,类似[weak self], 但是@noescape不能用于可选类型,因为可选类型实际上是enum,而非closure。

Generator.Element 是一个泛型定义,Element代表数组中的类型,它既可以是Int也可以是String等。像是对该泛型起了一个固定的名称叫:Element,而我们通常自定义泛型多喜欢用T。

以下是Generator的定义

public protocol GeneratorType {  
    /// The type of element generated by `self`.
    associatedtype Element
    /// Advance to the next element and return it, or `nil` if no next
    /// element exists.
    ///
    /// - Requires: `next()` has not been applied to a copy of `self`
    ///   since the copy was made, and no preceding call to `self.next()`
    ///   has returned `nil`.  Specific implementations of this protocol
    ///   are encouraged to respond to violations of this requirement by
    ///   calling `preconditionFailure("...")`.
    @warn_unused_result
    public mutating func next() -> Self.Element?
}

我门尝试着自己实现map函数:

//该实现不带有异常处理
func map<T>(transform: Element -> T) -> [T] {  
    var result: [T] = []
    for item in self {
      result.append(transform(item))
    }
    return result
  }

//调用方式:
[1, 2, 3].map { (x) -> Int in
  return x + 1
}
最近的文章

Swift 关键字:@noescape

Swift1.2发布时就已经有这个关键字了。正确使用它可以使我们避免许多不希望的保留环。 @noescape主要用在对函数中的closure参数修饰。 使用@noescape修饰closure后,cl…

继续阅读
更早的文章

Shell 脚本学习(-)

公司一位同事要离职,结果领导就把他负责的一些自动化工作交给我了,说是因为其他的同事都不懂shell,可是我也不懂啊。哎,很无奈,既然任务领导已经决定将任务交给我,那就是对我的信任。就这样对自己安慰着。…

继续阅读