higher order function in swift

Aug 20, 2021 Swift

High Order Functions Swift (Sorted, Map, Filter, Reduce)

  High Order Functions Swift : Higher order function are the function which operate on other function by taking the argument or return the function

To reduce the complicity in swift, they have introduced Higher order function in swift. Higher order function have some benefits  they are

  • Closure
  • Collection
  • Unwrapping optional
  • Argument Shortened

The Various Types of swift Higher order Function are

  1. map
  2. removeAll
  3. compactMap
  4. flatMap
  5. split
  6. filter
  7. reduce
  8. contains
  9. forEach
  10. sorted

High Order Functions Swift  are

Map :

     Map is used to loop over the items sequence and check the every argument of the function to return        the transform output.

    Consider an example :  we need to divide the elements of array by 2

let arrayNo = [ 2,4,6,8,10,12]

let arrayMapped = arrayNo.map { $0 / 2 }


Filter :

   Filter is the Function used when we needed to  filter specific element present the object

   Consider an example :  we need to filter  the elements of array which are greater then 5

let arrayNo =2,4,6,8,10,12]

let arrayfilter  = arrayNo.filter{ $0 > 5}



CompactMap is the same as the Map function but with optional handling capability.

    Consider an example :  we need to divide the elements of array by 2

let arrayNo =2,4,6,8,10,12]

let arraycomapct = arrayNo.compactMap { $0 > 5 }


    Print arrayMapped

Sorted :

Sorted is the function used to sort the model  in the sequence formate

let arraydata = [ 12,4,10,8,10,2]

let arraySorted = arraydata.sorted()


Reduce :

Reduce is used to combine all the elements to return the object

let arraydata = [ 12, 4, 10,8,10,2]

let arraySorted = arraydata.reduce("") { (result, value) in

    return result + String(value)