let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
let multiply: (Int, Int) -> Int = {x, y in x * y }
let total1 = numbers.reduce(3, multiply)
print(total1) // 120960
let total2 = numbers.reduce(3, {$0 * $1} )
print(total2) // 120960
let total3 = numbers.reduce(3, {(x: Int, y: Int) in
x * y
})
print(total3) // 120960
let total4 = numbers.reduce(3, {(x, y) in
x * y
})
print(total4) // 120960
reduce 取出数组中每一个元素,进行闭包中的操作,并返回与下一个元素进行闭包中的操作,直至结束,返回最终值,以上三种闭包用法都可以。
let numbers = [1, 2, 3, 4]
let mapped = numbers.map { Array(repeating: $0, count: $0) }
print(mapped) // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
print(flatMapped) // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
map 取出数组中的每一个元素,进行闭包中的操作,然后返回一个元素,组成新的数组
Array(repeating: 0) 返回一个数组,重复repeating count次
例如Array(repeating: 9, count: 3) 返回[9,9,9]
flatMap 取出数组中的元素,进行闭包中的变换,返回为一个single-level数组,并且会将nil值去掉
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.characters.count < 5 }
print(shortNames) // ["Kim", "Karl"]
filter 过滤集合中的元素。返回符合条件的集合
网友评论