美文网首页
swift中高阶函数

swift中高阶函数

作者: 心旷则神怡 | 来源:发表于2022-03-24 11:37 被阅读0次

    有些记不清了,随笔备忘,也参考了一些别人的

    1.map

    数组中的每一个元素调用一次该闭包函数,并返回该元素所映射的值。就是数组中每个元素通过某种规则(闭包实现)进行转换,最后返回一个新的数组,简单用法:

    //写法1
    var list = [10, 11, 12, 13]
    list = list.map({ res in
        return res + 2
    })
     print(list)//[12, 13, 14, 15]
    
    //写法2
    var list = [10, 11, 12, 13]
    list = list.map({
        $0 + 2//$0表示第几个参数,当前闭包只有一个参数所以是$0
     })
    print(list)//[12, 13, 14, 15]
    

    2. flatMap

    类似于map,区别就是,flatMap会把二维数组降为一维数组,其中有nil会移除

    let list1 = [[10, 11, 12, 13], [10, 11, 12, 13], [10, 11, 12, 13]]
    let list2 = list1.flatMap{$0}
     print(list2) //[10, 11, 12, 13, 10, 11, 12, 13, 10, 11, 12, 13]
    

    3.sort:排序

    let list1 = [13, 12, 14, 11]
    let list2 = list1.sorted(by: <)
    print(list2)//[11, 12, 13, 14]
    

    4.forEach:遍历

    // 准备一个数组,
    var array = ["A", "B", "C", "D", "E"]
    // 遍历
    array.forEach{ str in   
        print(str)
    }
    

    5.reduce:合归

    //求里面数组的和并排序
    let array = [[5,2,7],[4,8],[9,1,3]]
    let sumResult = array.map{$0.reduce(0, +)}.sorted(by: <)
    print(sumResult)//[12, 13, 14]
    
    //--------
    
    let array = [[5,2,7],[4,8],[9,1,3]]
    let sumResult = array.map{$0.reduce(0, {
        (res, ele) in
        return res + ele
    })}.sorted(by: <)
    print(sumResult)//[12, 13, 14]
    
    //---------
    
    let arr = ["a","b","c"]
    let resultStr: String = arr.reduce("i") { (result, element) -> String in
        print(element)
        return result + ", " + element
    }
    print(resultStr)
    //a
    //b
    //c
    //i, a, b, c
    

    6.filter: 对数组中元素进行条件筛选, 返回一个泛型数组

    let listStr = ["I", "hate", "this", "city"]
    let a = listStr.filter { res in
         return res != "I"
    }
    print(a)//["hate", "this", "city"]
    

    7.compactMap/compactMapValues: 过滤空值

    let listStr = ["1", "2", "d", "3", "4", "a"]
    let a = listStr.compactMap {
        Int($0)
    }
    print(a)//[1, 2, 3, 4]
    
    //-------
    let listStr:[String:String] = ["1":"1", "d":"2", "3":"3", "2":"d"]
    let a = listStr.compactMapValues { Int($0)}
    print(a)//["d": 2, "3": 3, "1": 1]
    

    8.mapValues转换value

    let dic: [String : Int] = ["a": 1, "b": 2, "c": 3, "d": 4 ]
     // 字典中的函数, 对字典的value值执行操作, 返回改变value后的新的字典
    let mapValues = dic.mapValues({ $0 + 2 })
    print(mapValues)//["a": 3, "b": 4, "c": 5, "d": 6]
    

    相关文章

      网友评论

          本文标题:swift中高阶函数

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