美文网首页Swift日常收录
Swift高阶函数常见使用

Swift高阶函数常见使用

作者: 文子飞_ | 来源:发表于2021-03-31 17:50 被阅读0次
    sort:排序
    // 准备一个数组
    var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
    // 这种默认是升序
    array.sorted()
    // 如果要降序
    array.sort { (str1, str2) -> Bool in
        return str1 > str2
    }
    
    forEach:遍历
    // 准备一个数组
    var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
    // 遍历
    array.forEach( { str in   
        print(str)
    });
    
    reduce:合归
    // map和filter方法都是通过一个已存在的数组,生成一个新的、经过修改的数组。然而有时候我们需要把所有元素的值合并成一个新的值
    var sum: [Int] = [11, 22, 33, 44]
    // reduce 函数第一个参数是返回值的初始化值 result是中间结果 num是遍历集合每次传进来的值
    var total = sum.reduce(0) { (result, num) -> Int in
        return result + num
    }
    print(total)
    
    first(where:) : 筛选第一个符合条件(Swift 4.1)
    var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
    let element = array.first(where: { $0.hasPrefix("A") })
    print(element!)
    // Animal
    
    last(where:) :筛选最后一个符合条件(Swift 4.2)
    var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
    let element = array.last(where: { $0.hasPrefix("A") })
    print(element!)
    // Aunt
    
    removeAll(where:):删除(Swift 4.2)。高效根据条件删除,比filter内存效率高,删除不想要的东西
    var array: [String] = ["Animal", "Baby", "Apple", "Google", "Aunt"]
    array.removeAll(where: { $0.hasPrefix("A") })
    print(array)
    // ["Baby", "Google"]
    
    allSatisfy:条件符合(Swift 4.2)
    // 判断数组的所有元素是否全部大于85
    // 检查序列中的所有元素是否满足条件,返回 Bool
    let scores = [86, 88, 95, 92]
    let passed = scores.allSatisfy({ $0 > 85 })
    print(passed)
    
    mapValues:转换value (Swift 4)
    let dic: [String : Int] = [
        "first": 1,
        "second": 2,
        "three": 3,
        "four": 4
    ]
    // 字典中的函数, 对字典的value值执行操作, 返回改变value后的新的字典
    let mapValues = dic.mapValues({ $0 + 2 })
    print(mapValues)
    
    compactMapValues:上面两个的合并(Swift 5)
    let dic: [String : String] = [
        "first": "1",
        "second": "2",
        "three": "3",
        "four": "4",
        "five": "abc"
    ]
    // 将上述两个方法的功能合并在一起,返回一个对value操作后的新字典, 并且自动过滤不符合条件的键值对
    let newDic = dic.compactMapValues({ Int($0) })
    print(newDic)
    
    map: 对数组中元素做一次处理, 返回一个泛型数组
    let arrayAny: [Any?] = [1, 2, 3, 4, 5, nil, "a", 8, "9"]
    print(arrayAny)
    let arrInt = arrayAny.map { (obj) -> Int in
        if obj is Int {
            return obj as! Int
        } else {
            return 0
        }
    }
    print("arrInt: \(arrInt)")
    // arrInt: [1, 2, 3, 4, 5, 0, 0, 8, 0]
    
    let arrInt2 = arrayAny.map {
        return ($0 is Int) ? $0 : 0
    }
    print("arrInt2: \(arrInt2)")
    // arrInt2: [Optional(1), Optional(2), Optional(3), Optional(4), Optional(5), Optional(0), Optional(0), Optional(8), Optional(0)]
    
    let tempArrays = gifJokeModels?.map({ (gifJokeModel) -> JDGifJokeModel in
            gifJokeModel.title += "&title"
            return gifJokeModel
    })
    
    flatMap 对数组中元素做一次处理,同时对最终的结果进行 “降维” ,过滤nil
    // 例1:flatMap 对最终的结果进行了所谓的 “降维” 操作
    let numbersCompound = [[1,2,3],[4,5,6]];
    var res = numbersCompound.map { $0.map{ $0 + 2 } }
    // [[3, 4, 5], [6, 7, 8]]
    var flatRes = numbersCompound.flatMap { $0.map{ $0 + 2 } }
    // [3, 4, 5, 6, 7, 8]
    
    // 例2:将原数组中的 nil 值过滤掉了,所有元素都被解包了
    let optionalArray: [String?] = ["AA", nil, "BB", "CC"];
    print(optionalArray)
    //[Optional("AA"), nil, Optional("BB"), Optional("CC")]
    
    var optionalResult = optionalArray.flatMap{ $0 }
    // ["AA", "BB", "CC"]
    
    filter: 对数组中元素进行条件筛选, 返回一个泛型数组
    let tempArrays = gifJokeModels?.filter({ (gifJokeModel) -> Bool in
                    return gifJokeModel.iD.intValue > 100
    })
    
    compactMap: 过滤空值
    // 返回操作的新数组(并不是筛选),数组、字典都可以使用
    // 它的作用是将 map 结果中那些 nil 的元素去除掉,这个操作通常会 “压缩” 结果,让其中的元素数减少
    let keys: [String?] = ["Zhangsan", nil, "Lisi", nil, "Wawngwu"]
    let validNames = keys.compactMap{ $0 }
    print(validNames)
    
    let counts = keys.compactMap { $0?.count }
    print(counts)
    
    // ["Zhangsan", "Lisi", "Wawngwu"]
    // [8, 4, 7]
    

    相关文章

      网友评论

        本文标题:Swift高阶函数常见使用

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