map(_:)
1 | func map<T>(_ transform: (Element) throws -> T) rethrows -> [T] |
map接受一个闭包***(Element) throws -> T***作为参数,然后返回闭包的返回值类型的数组
这个闭包接受Element类型的参数,这个类型代表数组中当前元素的类型。而这个闭包的返回值是可以和传递进来的值不同的。
比如我们可以这样:
1 | let numbers = [1,2,3,4] |
flatMap(_:)
1 | func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence |
就像他的名字一样,他会对数组进行降维,将数组拍扁。
compactMap(_:)
1 | func compactMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] |
其实原本 flatMap 是有两种重载的,他不但可以对数组进行降维,同时也可以充当filter的作用,过滤掉数组中nil的元素,后面觉得这样容易有歧义,所以把第二种重载换了个名字,就有了现在的compactMap。
例子:
1 | let data = ["a": "1", "b": "three", "c": "///4///"] |
这个的过滤是发生在输出结果的时候的 在闭包中出现nil也会被过滤掉
filter(_:)
1 | func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element] |
1 | let coins = [1, 5, 2, 10, 6, 2, 7, 4, 10, 15] |
reduce
1 | reduce(initialResult, (currentResult, currentElement) -> Return finalResult) |
1 | let coins = [1, 5, 2, 10, 6, 2, 7, 4, 10, 15] |
sort(by:) and sorted(by:)
sorted只返回一个数组的有序版本,不修改原数组。
sort无返回值,只会修改原数组。