Drop的使用
貌似這個(gè)不怎么常用,上代碼
var list:[Int] = [1,2,3,4,5,6,7,8,10]
let arr = list.drop { (item) -> Bool in
print("item:\(item)")
return item < 5
}
print(list)
print(arr)
輸出
item:1
item:2
item:3
item:4
item:5
[1, 2, 3, 4, 5, 6, 7, 8, 10]
[5, 6, 7, 8, 10]
drop函數(shù)是在閉包中去匹配是否符號(hào),只要不符合 后面就不執(zhí)行了,符合的話會(huì)一直執(zhí)行下去,我們把上面的item < 5
改成item > 5
var list:[Int] = [1,2,3,4,5,6,7,8,10]
let arr = list.drop { (item) -> Bool in
print("item:\(item)")
return item > 5
}
print(list)
print(arr)
輸出
item:1
[1, 2, 3, 4, 5, 6, 7, 8, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 10]
可見(jiàn)drop的閉包只執(zhí)行了一次
數(shù)組累加
let numbers = [1,2,3,4,5]
let sum = numbers.reduce(0) { total, num in
return total + num
}
print(sum)
輸出
15
對(duì)每個(gè)元素操作,返回一個(gè)新的數(shù)組
var list:[Int] = [1,2,3,4,5,6,7,8,10]
let newArr = list.map {(number: Int) -> Int in
return number * number
}
print(newArr)
輸出
[1, 4, 9, 16, 25, 36, 49, 64, 100]
過(guò)濾數(shù)組中需要的元素,返回一個(gè)新的數(shù)組
var list:[Int] = [1,2,3,4,5,6,7,8,10]
let newArr = list.filter { (number:Int) -> Bool in
return number % 2 == 0
}
print(newArr)
輸出
[2, 4, 6, 8, 10]
把二維數(shù)組拍扁
let array = [[1,2,3], [4,5,6], [7,8,9]]
let arrayFlatMap = array.flatMap { $0 }
print(arrayFlatMap)
輸出
[1, 2, 3, 4, 5, 6, 7, 8, 9]
上面的代碼也可以寫成這樣
let array = [[1,2,3], [4,5,6], [7,8,9]]
let arrayFlatMap = array.flatMap { (item: [Int]) -> [Int] in
return item
}
print(arrayFlatMap)
用reduce也能實(shí)現(xiàn),不過(guò)很少這么用
let array = [[1,2,3], [4,5,6], [7,8,9]]
let arrayFlatMap = array.reduce([]) { (total, num:[Int]) -> [Int] in
return total + num
}
print(arrayFlatMap)
能拍扁的不一定是二位數(shù)組,想把一個(gè)對(duì)象的內(nèi)部的一個(gè)變量數(shù)組全部取出來(lái)可以類似這樣,這個(gè)經(jīng)常會(huì)用到
var list:[(key:String,value:[Int])] = []
list.append((key: "calss1", value: [1,2,3,4,5,6]))
list.append((key: "calss2", value: [7,8,9,10]))
list.append((key: "calss2", value: [11,12,13,14]))
let arrayFlatMap = list.flatMap { (item:(key:String,value:[Int])) -> [Int] in
return item.value
}
print(arrayFlatMap)
輸出
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]