Drop的使用
貌似这个不怎么常用,上代码
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函数是在闭包中去匹配是否符号,只要不符合 后面就不执行了,符合的话会一直执行下去,我们把上面的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]
可见drop的闭包只执行了一次
数组累加
let numbers = [1,2,3,4,5]
let sum = numbers.reduce(0) { total, num in
return total + num
}
print(sum)
输出
15
对每个元素操作,返回一个新的数组
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]
过滤数组中需要的元素,返回一个新的数组
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]
把二维数组拍扁
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也能实现,不过很少这么用
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)
能拍扁的不一定是二位数组,想把一个对象的内部的一个变量数组全部取出来可以类似这样,这个经常会用到
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]