SyntaxStudy
Sign Up
Swift Higher-Order Functions
Swift Beginner 1 min read

Higher-Order Functions

Functions in Swift are first-class values — they can be stored in variables, passed as arguments, and returned from other functions. Function types are written as (ParamTypes) -> ReturnType. The standard library provides map, filter, reduce, sorted, compactMap, flatMap, and forEach for functional-style collection processing. Combining these higher-order functions with closures enables concise, expressive data transformations.
Example
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// map - transform each element
let squares = numbers.map { $0 * $0 }
// [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

// filter - keep elements matching predicate
let evens = numbers.filter { $0 % 2 == 0 }
// [2, 4, 6, 8, 10]

// reduce - fold into single value
let total = numbers.reduce(0, +)
// 55

// compactMap - map + unwrap optionals
let strings = ["1", "two", "3", "four", "5"]
let ints = strings.compactMap { Int($0) }
// [1, 3, 5]

// flatMap - flatten nested collections
let nested = [[1, 2], [3, 4], [5, 6]]
let flat = nested.flatMap { $0 }
// [1, 2, 3, 4, 5, 6]

// Chain operations
let result = numbers
    .filter { $0 % 2 == 0 }
    .map { $0 * $0 }
    .reduce(0, +)
print(result)  // 220

// Function as parameter
func applyTwice(_ f: (Int) -> Int, to value: Int) -> Int {
    f(f(value))
}
let double = { (x: Int) -> Int in x * 2 }
print(applyTwice(double, to: 3))  // 12