Higher-Order Functions
Higher-order functions are functions that either take one or more functions as arguments or return a function as their result. In Swift, these are commonly used with collections to write expressive, declarative code.
Map
map iterates over a collection and transforms every item using a named function or a closure you provide. It returns a new array containing the transformed items.
let numbers = [1, 2, 3, 4, 5]
// Double every number
let doubled = numbers.map { (number: Int) -> Int in
return number * 2
}
print(doubled) // [2, 4, 6, 8, 10]Filter
filter iterates over a collection and returns a new array containing only the elements that satisfy a specific condition.
let names = ["Jack", "James", "Anne", "John"]
// Filter names starting with 'J'
let jNames = names.filter { (name: String) -> Bool in
return name.hasPrefix("J")
}
print(jNames) // ["Jack", "James", "John"]Reduce
reduce combines all items in a collection into a single value. It takes an initial value and a named function or a closure that describes how to combine the current accumulated value with the next item.
let prices = [10, 20, 30, 40]
// Sum all prices starting from 0
let total = prices.reduce(0) { (runningTotal: Int, nextPrice: Int) -> Int in
return runningTotal + nextPrice
}
print(total) // 100CompactMap
compactMap is similar to map, but it automatically removes nil values from the resulting array. This is extremely useful when converting types that might fail.
let strings = ["1", "2", "three", "4", "five"]
// Convert to Int? and remove nil values
let ints = strings.compactMap { Int($0) }
print(ints) // [1, 2, 4]Sorted
sorted returns a new collection that is sorted based on a named function or a closure that compares two elements.
let unsorted = [5, 1, 4, 2, 3]
// Sort descending
let descending = unsorted.sorted { $0 > $1 }
print(descending) // [5, 4, 3, 2, 1]