1.map函數(shù)
(Return an Array
containing the results of mapping transform
)map函數(shù)對數(shù)組元素進行某種規(guī)則的轉(zhuǎn)換并返回一個新的數(shù)組
let arr = [1,2,4,5]
let brr = arr.map {
"No."+String($0) 將元素轉(zhuǎn)換為字符串并拼接No.
//$0+1 //將所有元素都加1
}
brr------>["No.1", "No.2", "No.4", "No.5"]
2.flatMap函數(shù)
flatMap函數(shù)有兩種重載形式菩混。這兩個重載的函數(shù)都是接受一個閉包作為參數(shù)阵谚,返回一個數(shù)組担钮。
public func flatMap<S : SequenceType>(transform: (Self.Generator.Element) throws -> S) rethrows -> [S.Generator.Element]
(Self.Generator.Element) -> S提陶,并且這里 S 被定義成:S : SequenceType呼畸。所以它是接受數(shù)組元素让腹,然后輸出一個 SequenceType 類型的元素的閉包
let arr1 = [[1,2,3],[6,5,4]]
let frr = arr1.flatMap {$0} --->[1, 2, 3, 6, 5, 4]
let grr = Array(arr1.map { $0 }.flatten()) ---->[1, 2, 3, 6, 5, 4]
public func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]
flatMap 最終輸出的數(shù)組結(jié)果焦读,其實不是這個 T? 類型仓蛆,而是這個 T? 類型解包之后,不為 .None 的元數(shù)數(shù)組:[T]
Return an `Array` containing the non-nil results of mapping 返回一個沒有nil的map過的數(shù)組
let arr2:[Int?] = [1,2,nil,4,nil,5]
let hrr = arr2.flatMap {
$0
}
hrr -----> [1, 2, 4, 5]
flatMap 將數(shù)組中nil都丟棄了蝌诡。只保留非空的值
3.reduce函數(shù)
來對數(shù)組元素進行某種規(guī)則的求和(不一定是加和)
Return the result of repeatedly calling combine
with an
accumulated value initialized to initial
and each element of self
, in turn
public func reduce<T>(initial: T, @noescape combine: (T, Self.Generator.Element) throws -> T) rethrows -> T
initial:初始化的值溉贿,combine方法
let crr = arr.reduce(0) { (pre:Int, element:Int) -> Int in
return pre+element
}
上例中initial=0,也就是從0開始用某種規(guī)則求和。
pre表示:之前求和的結(jié)果 ---> 一開始是0
element:表示即將進入運算的數(shù)組中的元素 ---->第一個是 1
pre+element:表示求和的規(guī)則 ---->閉包里面的規(guī)則自己定義
其他規(guī)則的求和
let drr = arr.reduce("") {
if $0 == ""{
return String($1)
}else{
return $0+" "+String($1)
}
}
drr ------> "1 2 4 5"
4.filter函數(shù)
返回符合條件的元素的數(shù)組
public func filter(@noescape includeElement: (Self.Generator.Element) throws -> Bool) rethrows -> [Self.Generator.Element]
let err = arr.filter { (num:Int) -> Bool in
num%2==0 //需要符合的條件浦旱。
}
err -----> [2, 4]