Swift 的高阶函数,map、flatMap、filter、reduce

之前学习 Python 的时候,觉得还不错,然后发现 Swift 里面也有。

1、map 函数 — 对数组中的每一个对象做一次运算

        let stringArray = ["Objective-C", "Swift", "Python", "HTML5", "C",""]
        
        let resultAry = stringArray.map { (element) -> Int? in
            if element.length > 0 {
                return element.length
            }else{
                return nil
            }
            
        }
        print(resultAry)
        //[Optional(11), Optional(5), Optional(6), Optional(5), Optional(1), nil]

2、fiatMap 函数 — 也是对每个对象做一次运算,但是有区别

区别1 不会返回 nil ,会把 optional 类型解包

        let stringArray = ["Objective-C", "Swift", "Python", "HTML5", "C",""]
        let resultAry = stringArray.flatMap { (element) -> Int? in
            if element.length > 0 {
                return element.length
            }else{
                return nil
            }
            
        }
        print(resultAry)
        //[11, 5, 6, 5, 1]

区别2 会把N 维数组变成成一个 1维 数组 返回

        let stringArray = [["Objective-C", "Swift"], ["Python", "HTML5", "C",""]]
        
        let resultAry = stringArray.map { $0 }
        print(resultAry)
        //[["Objective-C", "Swift"], ["Python", "HTML5", "C", ""]]

        //flatMap
        let stringArray = [["Objective-C", "Swift"], ["Python", "HTML5", "C",""]]
        
        let resultAry = stringArray.flatMap { $0 }
        print(resultAry)
        //["Objective-C", "Swift", "Python", "HTML5", "C", ""]

3、filter 过滤,数组中的元素按照 闭包里面的规则过滤

        let stringArray = ["Objective-C", "Swift", "Python", "HTML5", "C",""]
        
        let resultAry = stringArray.filter { (element) -> Bool in
            //元素长度大于5的 取出
            return element.length >= 5
        }
        print(resultAry)
        //["Objective-C", "Swift", "Python", "HTML5"]

4、reduce 计算,按顺序对数组中的元素进行操作,然后记录操作的值再进行下一步相同的操作,可以想象成累加。

        let stringArray = ["Objective-C", "Swift", "Python", "HTML5", "C",""]
        
        let resultStr = stringArray.reduce("Hi , I'm PierceDark,") { (element1, element2) -> String in
            return element1 + " ," + element2
        }
        print(resultStr)
        //Hi , I'm PierceDark, ,Objective-C ,Swift ,Python ,HTML5 ,C ,

这里就是这几个函数的基本使用了,不过这些函数的编译需要时间都比较久(和三目运算符一样),如果需要缩短编译时间,那么还得写 for循环。。 只不过阅读起来就没这么舒服了。

    原文作者:PierceDark
    原文地址: https://www.jianshu.com/p/a75624ca0b8c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞