今年夏天接触 Python 的时候,发现 Python 中有高阶函数(Higher-order function)的用法,RN中使用Epic进行异步处理数据时也用到了map、flatMap,其实 swift 中也是可以使用高阶函数(map、flatMap、filter、reduce)的,这种函数式编程也是相比 Objective-C 的一大优点。
简单来说,高阶函数就是函数的嵌套,其中被嵌套的函数也就是我们常说的闭包。下面就对这几种高阶函数分别进行讲解。
map: 对集合类型中的每一个元素通过某个方法进行处理。
// MARK: 取数组中每个元素的相反数 let numbers = [0,1,4,-5,99,-23] //传统方法 func oppositeArr(arr: [Int]) -> [Int] { var oppositeArr: [Int] = [] for number in arr { oppositeArr.append(-number) } return oppositeArr } func oppositeNumber(num: Int) -> Int { return -num } // 使用 map func map1() { // 多种写法 let oppositeArr1 = numbers.map(oppositeNumber) let oppositeArr2 = numbers.map({ num in -num }) let oppositeArr3 = numbers.map({ return -$0 }) let oppositeArr4 = numbers.map({-$0}) print(oppositeArr1,oppositeArr2,oppositeArr3,oppositeArr4) // 结果都是 [0,-1,-4,5,-99,23] } // MARK: 在数组每一个元素钱加“¥”,并返回string类型的数组 let priceArr: [Float] = [12,12.2,32,45] // 传统方法 func formatPrice(arr: [Float]) -> [String] { var priceStrArr:[String] = [] for price in priceArr { priceStrArr.append("¥\(price)") } return priceStrArr } func priceToStr(price: Float) -> String { return "¥\(price)" } // 使用 map func map2() { // 多种写法 let priceStrArr1 = priceArr.map(priceToStr) let priceStrArr2 = priceArr.map { price in "¥\(price)"} let priceStrArr3 = priceArr.map { return "¥\($0)" } let priceStrArr4 = priceArr.map { "¥\($0)" } print(priceStrArr1,priceStrArr2,priceStrArr3,priceStrArr4) // 结果都是 ["¥12.0","¥12.2","¥32.0","¥45.0"] }
flatMap:对集合类型中的每一个元素通过某个方法进行处理,同时进行解包或重载。
与map的相同之处
let numSet = [1,2,3,4] let square = numSet.map { $0 * $0 } let flatSquare = numSet.flatMap { $0 * $0 } print(square) // [1,9,16] print(flatSquare) // [1,16]
对optional解包
let arr = ["a.png","b.png",nil,"c.png"] let mapArr = arr.map { $0 } let flatArr = arr.flatMap { $0 } print(mapArr) // [Optional("a.png"),Optional("b.png"),Optional("c.png")] print(flatArr) // ["a.png","c.png"]
对多维数组进行重载
let numbersCompound = [[1,3],[4,6]]; let res = numbersCompound.map { $0.map{ $0 + 2 } } print(res) // [[3,5],[6,7,8]] let flatRes = numbersCompound.flatMap { $0.map{ $0 + 2 } } print(flatRes) // [3,6,8]
filter: 过滤操作,对集合内的元素按某一规则进行过滤。
let arr = [1,6] let newArr = arr.filter { $0 % 2 == 1 } print(newArr) // [1,5] let strArr = ["布怀特","is","a","大帅逼",""] let filter = strArr.filter { $0 != nil && $0!.count > 0 } print(filter) // [Optional("布怀特"),Optional("is"),Optional("a"),Optional("大帅逼")]
reduce: 计算操作,对集合内的元素进行“计算”
let numArr = [1,2] let reduceArr1 = numArr.reduce(0,{$0 + $1}) let reduceArr2 = numArr.reduce(1,*) print(reduceArr1,reduceArr2) // 10 24 let strArr = ["布怀特"," is"," a "," 大帅比","!"] let reduceStrArr1 = strArr.reduce("",{$0 + $1}) let reduceStrArr2 = strArr.reduce("",+) print(reduceStrArr1,reduceStrArr2) // 布怀特 is a 大帅比! 布怀特 is a 大帅比!原文链接:https://www.f2er.com/swift/320816.html