Swift-高阶函数如map,reduce,filter的一些总结

闾丘康安
2023-12-01

Swift 这个语言,速度快,更加安全,代码少,易于阅读维护. 所以一些高阶函数在项目实际使用中也是蛮方便的总结如下:

高阶函数的定义:一个函数如果可以以某个函数作为参数,或者返回值,那么这个函数就称之为高阶函数,如map,reduce,filter.

map: 对数组中的元素进行处理.返回的是数组中每个元素经过处理的数组.

filter:过滤数组中不符合条件的元素. 返回的是一个符合要求的数组.

reduce: 将数组中的元素进行一些操作,如数组是Int型可求和,String 类型可把数组中元素合并成一个String.

一下是一些例子:

map:

例子1:

func make13() {
        let stringArr = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"]
        //方式1
        let resultStrArr1 = stringArr.map(stringCount)
        //方式2
        let resultStrArr2 = stringArr.map { (str) -> Int in
            return str.count
        }
        //方式3
        let resultStrArr3 = stringArr.map({$0.count})
        print(resultStrArr3)// [11, 5, 4, 3, 10]
    }
    func stringCount(str: String) -> Int {
        return str.count
    }

例子2:

func make12() {
        let tool = TestTools()
        tool.name = "dongfei"
        tool.age = 18
        let toolArr = [tool, tool, tool]
        // 方式1
        toolArr.map(reviseAge)
        
        //方式2
        var resultTool = toolArr.map { (tool) -> TestTools in
            tool.age = 20
            return tool
        }
    }
    
    func reviseAge(tool: TestTools) -> TestTools {
        tool.age = 20
        return tool
    }

filter:

func make15() {
        let stringArr = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"]
        let arr1 = stringArr.filter(stringCountLess10)
        let arr2 = stringArr.filter { (str) -> Bool in
            return str.count < 10
        }
        let arr3 = stringArr.filter {
            return $0.count < 10
        }
        print(arr3)//["Swift", "HTML", "CSS"]
    }
    
    func stringCountLess10(str: String) -> Bool {
        return str.count < 10
    }

reduce:

func make14() {
        let stringArr = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"]
        let arr1 =  stringArr.reduce("", appendSting)
        let arr2 = stringArr.reduce("") { (str1, str2) -> String in
            return str1 == "" ? str2 : str1 + "," + str2
        }
        let arr3 = stringArr.reduce("") {
            return $0 == "" ? $1 : $0 + "," + $1
        }
        print(arr3)//Objective-C,Swift,HTML,CSS,JavaScript
    }
    
    func appendSting(str1: String, str2: String) -> String
    {
        return str1 == "" ? str2 : str1 + "," + str2
    }

map 与flatmap的区别

1 flatmap 返回后的数据中不存在nil,同时它会把Optional 解包

func make16() {
        let array = ["Apple", "Orange", "Puple", ""]
        let arr1 = array.map { (a) -> Int? in
            let length = a.count
            guard length > 0 else {return nil}
            return length
        }
        print(arr1)//[Optional(5), Optional(6), Optional(5), nil]
        let arr2 = array.flatMap { (a) -> Int? in
            let length = a.count
            guard length > 0 else {return nil}
            return length
        }
        print(arr2)//[5, 6, 5]
    }

2 flatMap 还能把数组中存在有数组的数组一同打开变成一个新的数组:

func make17() {
        let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
        let arr1 = array.map{ $0 }
        print(arr1) // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
        let arr2 = array.flatMap{ $0 }
        print(arr2) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
    }

3 flatMap也能把两个不同的数组合并成一个数组,这个合并的数组元素是前面两个数组元素个数的成绩.

func make18() {
        let fruits = ["Apple", "Orange", "Puple"]
        let counts = [2, 3, 5]
        
        let array = counts.flatMap { count in
            fruits.map ({ fruit in
                return fruit + "  \(count)"
            })
        }
        print(array) // ["Apple 2", "Orange 2", "Puple 2", "Apple 3", "Orange 3", "Puple 3", "Apple 5", "Orange 5", "Puple 5"]
    }
 类似资料: