用 reduce 方法一次求出數(shù)組中奇數(shù)的和、以及偶數(shù)乘積
let arr1 = [1,3,2,4]
let ress:(Int,Int) = arr1.reduce((0,1)) { (a:(Int,Int), element) -> (Int,Int) in
if element % 2 == 0 {
return (a.0,a.1 * element)
}else {
return (a.0 + element, a.1)
}
}
reduce 方法實(shí)現(xiàn) map 的功能
let arr = [1,3,2]
let res = arr.reduce([]) { (a:[Int], element) -> [Int] in
var t = Array(a)
t.append(element * 2)
return t
}
求一個(gè)數(shù)組中偶數(shù)的平方和
let arr3 = [1,3,2,4]
let rr = arr3.filter {
$0 % 2 == 0
}.map {
$0 * $0
}.reduce(0) {
$0 + $1
}
print(rr)
}