Use Higher-Order Functions in Swift
Written by Team Kodeco
A higher-order function is a function that takes one or more functions as input and/or returns a function. In Swift, functions are first-class citizens, which means they can be passed as arguments to other functions, stored in variables and constants, and returned from functions.
Here is an example of a higher-order function that takes two functions as input and returns a new function that applies the two input functions in sequence:
// Define two simple functions
func addTwo(number: Int) -> Int {
return number + 2
}
func multiplyByThree(number: Int) -> Int {
return number * 3
}
// Define the higher-order function
func compose(
firstFunction: @escaping (Int) -> Int,
secondFunction: @escaping (Int) -> Int
) -> (Int) -> Int {
return { (input: Int) -> Int in
return secondFunction(firstFunction(input))
}
}
// Use the higher-order function to compose the two simple functions
let composedFunction = compose(firstFunction: addTwo, secondFunction: multiplyByThree)
// Use the composed function
let result = composedFunction(2)
print(result) // Output: 12
A Higher-order function can be thought of as a factory that produces a new function. It takes some functions as input and returns a new function that combines them in some way.
A common use case for higher-order functions is to abstract away some common logic and make it reusable across different parts of the codebase.
Note: The @escaping keyword is used here to indicate that the functions you passed in as input to
compose
will be called aftercompose
returns.