SoFunction
Updated on 2025-04-11

Swift commonly used higher-order functions

map

var arr = [1, 2, 3]
//The map function has a return value. If you want the value in arr, map in the past, you need arr to receive a new value again. { (a : Int) -> Int in
  return a * 2
}
//This writing is just the abbreviation for trailing closures.  .arr =  {
  $0 * 2
}

flatMap

//FloatMap function can reduce dimensionalityvar arr1 = [[1, 2], [4, 5], [6, 7]]
var aaa =  {
  $0
}
//The floatMap function removes the empty function and will also unpack the datavar arr2 = ["swift", nil, "java"]

var bbb =  {
  $0
}

filter

//Filter function is used to filter elements in containervar arr3 = ["swift", "java", "oc", "python"]
arr3 =  {
  guard $ > 2 else {
    return false
  }
  return true
}

reduce

//Reduce function is used to operate on elements in containers and splice element stringsvar arr4 = [2, 3, 4, 5]
//("", {
//  return $0 == "" ? String($1) : $0 + String($1)
//})
//Sum with reduce(0) {
  return $0 + $1
}
// Stitch each string in the array with ','let arr5 = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"]

// $0 represents the calculated result, $1 represents each element in the array("", {
  return $0 == "" ? $1 : $0 + "," + $1
})

Therefore, the higher-order functions and closures of the Swift language can capture the characteristics of external variables, so that the code logic can be encapsulated with functions as the main body, which will make our code organization more flexible.

Of course, if abused, this can also make the code organization even more confusing.