map 遍历
let numbers = [1,2,3]
let sumNumbers = numbers.map { (number: Int) -> Int in
return number + number
}
let numbers = [1,2,3]
let sumNumbers = numbers.map { $0+$0
}
flatmap 返回的数据中不存在nil,并且是解包之后的数据
let array = [[1,2,3], [4,5,6], [7,8,9]]
// 如果用map来获取新的数组
let arrayMap = array.map { $0 }
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(arrayMap)
// 用flatMap
let arrayFlatMap = array.flatMap { $0 }
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(arrayFlatMap)
filter 筛选
let numbers = [1,2,3,4,5,6]
let evens = numbers.filter { $0 % 2 == 0 }
// [2, 4, 6]
print(evens)
reduce
let numbers = [1,2,3,4,5]
// reduce 函数第一个参数是返回值的初始化值
let sum = numbers.reduce(0) { $0 + $1 }
// 这里我写下完整的格式
let sum1 = numbers.reduce(0) { total, num in
// 这里写不写return在Playground都循环5次 但上面用最洁简的方法显示循环6次。。。 What The Fuck 这是什么鬼!!!
return total + num
}
// 15
print(sum)
let numbers = [1,5,1,8,8,8,8,8,8,8,8]
// reduce 函数第一个参数是返回值的初始化值
let tel = numbers.reduce("") { "($0)" + "($1)" }
// 15188888888
print(tel)
网友评论