Higher order functions in Swift are functions that can either take other functions as parameters or return functions as outputs. These functions enable a more concise and expressive way of working with collections and data manipulation. In this tutorial, we will explore some common higher order functions in Swift and demonstrate how they can be used in practice.
The map
function applies a given closure to each element in a collection and returns an array of the results. This is useful for transforming each element in a collection without mutating the original data.
let numbers = [1, 2, 3, 4, 5]
let squaredNumbers = numbers.map({ $0 * $0 })
print(squaredNumbers) // Output: [1, 4, 9, 16, 25]}
The filter
function creates a new array containing only the elements that satisfy a given condition specified by a closure. It is useful for selecting elements that meet certain criteria.
let evenNumbers = numbers.filter({ $0 % 2 == 0 })
print(evenNumbers) // Output: [2, 4]}
The reduce
function combines all elements in a collection using a specified closure. It takes an initial value and a closure that combines the elements in the collection. This is useful for collapsing a collection into a single value.
let sum = numbers.reduce(0, { $0 + $1 })
print(sum) // Output: 15}
The compactMap
function is used to transform and unwrap elements in a collection, discarding any nil values. It is particularly useful when working with optional values.
let optionalNumbers: [Int?] = [1, nil, 3, nil, 5]
let validNumbers = optionalNumbers.compactMap({ $0 })
print(validNumbers) // Output: [1, 3, 5]}
By leveraging these higher order functions in Swift, you can write more declarative and readable code when working with collections and data manipulation tasks. Experiment with these functions in your own projects to discover additional ways they can simplify your code.