map,reduce,filter,flatmap

来源:互联网 发布:怎么在淘宝搜同款 编辑:程序博客网 时间:2024/06/05 00:47

swift 的这些语法可以让代码更简洁,有木有想起javascript 也有类似的语法 我觉得其无非是通过一个闭包将数组或集合等在闭包处理一下返回一个结果。

map

一个方法,闭包内返回一个泛型,那说明允许对数组进行类型转换

var values = [2.0,3.0,4.0,5.0]

如果我们想要将上述数组进行逐项平方,最容易想到的是遍历数组,然后对每项平方
var nValues = [Double]()
for value in values {
nValues.append(value * value)
}

但是,使用map 可以简化些了
let sqares = values.map { (value) -> Double in
return value * value
}

这里返回一个不可变数组,安全点吧~

简化点
let squeres = values.map{ value in return value * value }

再简化些
let squres = values.map{$0 * $0}

搞个数字转拼音玩玩
let scores = [0,28,124]
let words = scores.map { (score) -> String in
return NumberFormatter.localizedString(from: NSNumber.init(value: score), number: .spellOut)
}

简化点呢
let words = scores.map{NumberFormatter.localizedString(from: NSNumber.init(value: $0), number: .spellOut)}

打印结果:["zero", "twenty-eight", "one hundred twenty-four"]

Filter

只有一个方法闭包内必须返回一个bool

let nums = [1,2,3,5,6]
let event = nums.filter { (num) -> Bool in
return num % 2 == 0
}

简化点
let event = nums.filter{$0 % 2 == 0}

Reduce

参数之间处理闭包内返回一个结果,有一个预设值,可以进行比较或运算

let items = [2.0,4.0,5.0,7.0]

let totals = items.reduce(10) { (result, item) -> Double in
return result - item
}

忽略这个预设值那就设置为0

let totls = items.reduce(0) { (result, item) -> Double in
return result + item
}

简化点
let totals = items.reduce(0,+)

flatMap

有两个方法,闭包内可以返回一个序列,也可以返回一个可选值
let collects = [[2,3,4,5],[1,5,6],[2,4]]
合并元素
let tess = collects.flatMap { $0 }
类型转换闭包内返回数组,配合map
let tess = collects.flatMap { (tests) -> [Double] in
return tests.map({ (t) -> Double in
return Double(t)
})
}

闭包内返回可选值,配合reduce
let tess = collects.flatMap { (tests) -> Int? in
return tests.reduce(0, { (ls, lh) -> Int in
return ls + lh
})
}

返回一个数组,配合filter

let tess = collects.flatMap {
param in param.filter { $0 % 2 == 0}
}

对元素平方,两个$0代表的含义不同

let tess = collects.flatMap{ $0.map { $0 * $0} }

字符串可以自动删除nil

let strs = ["li","wang",nil,"xiao","zhang",nil]

let nstrs = strs.flatMap{$0}

相互配合链式处理

let digs = [8,4,3,6,7]

let tots = digs.filter{$0 >= 5}.reduce(0,+)

print(tots)

let sqevent = digs.map{$0 * $0}.filter{$0 % 2 == 0}

print(sqevent)