美文网首页iOS面试专题
swift 之 高阶函数(一)

swift 之 高阶函数(一)

作者: 90后的晨仔 | 来源:发表于2020-02-10 16:58 被阅读0次
    1. filter函数,过滤(筛选)不满足条件的元素,返回满足条件的元素组成数组。
    func filter(_ isIncluded: (UInt8) throws -> Bool) rethrows -> [UInt8]
    

    简述:filter方法参数是一个闭包,闭包返回值是Bool类型,当满足筛选条件的时闭包才有返回值,filter返回值是一个<T>的泛型数组

    使用方法:
    let array = [1,2,3,4]
    let filteredArray = array.filter{$0 > 2}//$0代表闭包的第n+1个参数(这里代表数组中的元素)
    print(filteredArray)
    //输出新的数组[3, 4]
    

    分析:上边的例子其实等价于下边的例子

    var tempArr = [Int]()
    for s in array {
        if s > 2 {
        tempArr.append(s)
        }
    }
    print(tempArr)
    
    struct PackageInfo{
        var name:String
        var number:Int
        var price:Float
        var address:String
    }
    let testInfo = [
        PackageInfo(name: "测试1", number: 1, price: 1111, address: "阿西西"),
        PackageInfo(name: "测试2", number: 2, price: 882.0, address: "哈哈"),
        PackageInfo(name: "测试3", number: 3, price: 35.0, address: "7哈哈"),
        PackageInfo(name: "测试4", number: 4, price: 50.0, address: "oo")
    ]
    
    let testDemo = testInfo.filter{(package) -> Bool in
        return package.price == 111
    }
    print(testDemo)
    
    2.map可以对数组中的每一个元素做一次处理, 返回一个泛型的数组。

    参考链接:https://www.jianshu.com/p/56f75313c8ea

    使用方法:
    (1)、简单使用
    let array = [1,2,3,4]
    let testMapArray = array.map{$0 * 10}
    print(testMapArray)
    
    (2)、常见的使用方法
    let stringArray = ["Objective", "Swift", "HT", "CS", "Java"]
    let arrayCount = stringArray.map { (str) -> Int in
          return str.count
    }
    
    let arraArr: [Any?] = [0,1,2,4,5,nil,"abc",9,"109"]
    let arrInt = arraArr.map { (obj) -> Int in
        if obj is Int {
            return obj as! Int
        } else {
            return 0
        }
    }
    print("arrInt: \(arrInt)")
    

    注释:
    is操作符:若一个类属于另一个类的子类,则会返回true,否则返回false。
    as操作符:as(向上转换)、as?(向下转换) 、as!(强制解包)
    详解可以看看这篇博客我觉着分析的挺好的:https://www.jianshu.com/p/edbdc60218d1

    3. reduce 把集合中所有的值结合起来返回一个新的值。
    (1)、计算数组中数字的和
    var dataArr = [3, 5, 6, 7, 8]
    var totalValue = dataArr.reduce(0) { $0 + $1 }
    print(totalValue)
    
    
    (2)、把所有地址那出来
    struct PackageInfo{
        var name:String
        var number:Int
        var price:Float
        var address:String
    }
    let testInfo = [
        PackageInfo(name: "测试1", number: 1, price: 1111, address: "阿西西"),
        PackageInfo(name: "测试2", number: 2, price: 882.0, address: "哈哈"),
        PackageInfo(name: "测试3", number: 3, price: 35.0, address: "7哈哈"),
        PackageInfo(name: "测试4", number: 4, price: 50.0, address: "oo")
    ]
    
    let reduceName = testInfo.reduce("") {$0 + $1.address}
    

    相关文章

      网友评论

        本文标题:swift 之 高阶函数(一)

        本文链接:https://www.haomeiwen.com/subject/itnaxhtx.html