swift 高阶函数

1. flatMap 降纬 组成一个新的一维数组

    let arr = [[1, 2, 3], [4, 5],nil]
    let arr1 = [[1, 2, 3], [4, 5]]
    let newArr = arr.flatMap{
        $0
    }
    let newArr1 = arr1.flatMap{
        $0
    }
    print(newArr)
    print(newArr1)
    newArr:[[1, 2, 3], [4, 5]]
    newArr1:[1, 2, 3, 4, 5]

tip:可以将二维数组转化为一维数组,如果有空值则不会降纬

2. compactMap 过滤nil 组成一个新的数组

    let arr = [1, 2, 3, nil, nil, 4, 5]
    let newArr = arr.compactMap{$0}
    print(newArr)
    newArr: [1, 2, 3, 4, 5]

3. filter 选择集合中符合条件的元素,过滤掉不符合条件的元素

    let arr = [5, 4, 3, 1, 2]
    let newArr = arr.filter { (item) -> Bool in
        return item > 3
    }
    debugPrint(newArr)
    newArr:[5, 4]

4. reduce 可以将一个集合中的所有元素组合起来,生成一个新的值并返回该值

    let numbers = [1, 2, 3, 4]
    let numberSum = numbers.reduce(4, { x, y in
      return  x + y
    })
    debugPrint(numberSum)
    numberSum:14

5. firstIndex 返回数组中最先匹配到该元素的索引值

    let num = [11,22,33,44,55,33,44,66]
    print(num.firstIndex(of: 44))
    index:Optional(3)

6. lastIndex 返回数组中最后匹配到该元素的索引值

    let num = [11,22,33,44,55,33,44,66]
    print(num.lastIndex(of: 44))
    index:Optional(6)

7. firstIndex(where: {})查找数组中符合条件的元素的索引值

    let num = [11,22,33,44,55,33,44,66]
    print(num.firstIndex(where: {$0 == 44}))
    index:Optional(3)

8. Contains 查找数组中的元素是否满足一个条件

   let arr = [2,5,8,7,10,33]
   let result = arr.contains { num -> Bool in
        return num % 7 == 0
   }
   print(result)

9.排序

        let arr = [2,1,4,3]
        let newArr = arr.sorted { (num1, num2) -> Bool in
            return num1 > num2
        }
        debugPrint(newArr)

你可能感兴趣的:(swift 高阶函数)