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
}
