Swift高阶函数介绍
2019-10-10 本文已影响0人
BigBossZhu
最近了解Swift函数式编程,函数式编程的思想就是一切皆函数,函数作为一等公民,可以是被当作变量,参数,返回值。个人理解函数式编程,就是高阶函数编程的应用。所以要熟练掌握基础的高阶函数是必须的filter,map,reduce,flatmap就是必备的高阶函数。这里的$n表示的是闭包的第n + 1个参数,这是swift的基础,不多做记录
filter
Swift中的filter函数的作用就是接受一个闭包作为筛选规则,自动遍历集合的每一个元素,保留符合闭包规则的元素,生成一个新的集合
struct Package{
var name:String
var number:String
var price:Float
var address:String
}
let packages = [
Package(name: "Swift高阶函数编程", number: 1, price: 80.0, address: "中关村"),
Package(name: "Swift面向协议编程", number: 2, price: 88.0, address: "西二旗"),
Package(name: "Swift基础", number: 3, price: 35.0, address: "798"),
Package(name: "Swift进阶", number: 4, price: 50.0, address: "望京soho")
]
let package80s = packages.filter { (package) -> Bool in
return package.price == 80
}
print(package80s)
package80s = packages.filter {$0.price == 80}
print(package80s)
map
Swift中的map函数的作用就是接受一个闭包作为规则,自动遍历集合的每一个元素,使用闭包的规则去处理这些元素,生成一个结构相同的集合
//将每一个元素的name作为新数组的元素
let let packageNames = packages.map {$0.name}
flatMap
Swift中的flatMap函数的作用就是接受一个闭包作为规则,自动遍历集合的每一个元素,使用闭包的规则去处理这些元素,将处理结果直接放入到一个新的集合里面,可以出现数组降维,并且会自动过滤nil(自动解包),如果是不包含nil元素的一维数组的和map的作用效果是一样的,所以推荐使用flatMap
let packages = [
Package(name: "Swift高阶函数编程", number: 1, price: 80.0, address: "中关村"),
Package(name: "Swift面向协议编程", number: 2, price: 88.0, address: "西二旗"),
Package(name: "Swift基础", number: 3, price: 35.0, address: "798"),
nil,
Package(name: "Swift进阶", number: 4, price: 80.0, address: "望京soho")
]
let packageNames = packages.flatMap { (package) -> String? in
return package?.name
}
reduce
Swift中的reduce函数的作用就是接受一个初始化值,并且接受一个闭包作为规则,自动遍历集合的每一个元素,使用闭包的规则去处理这些元素,合并处理结果
Returns the result of combining the elements of the sequence using the given closure(重点在于combining)
let packages = [
Package(name: "Swift高阶函数编程", number: 1, price: 80.0, address: "中关村"),
Package(name: "Swift面向协议编程", number: 2, price: 88.0, address: "西二旗"),
Package(name: "Swift基础", number: 3, price: 35.0, address: "798"),
Package(name: "Swift进阶", number: 4, price: 50.0, address: "望京soho")
]
let reduceName = packages.reduce("") {$0 + $1.name}
//reduceName = "Swift高阶函数编程Swift面向协议编程Swift基础Swift进阶"