Swift Tutorial
Swift Data Types
Swift Control Flow
Swift Functions
Swift Collections
Swift OOPs
Swift Additional Topics
Higher-order functions in Swift refer to functions that either take one or more functions as arguments, return a function, or both. Swift's standard library, particularly the Array
and Sequence
types, provides several higher-order functions that enable powerful and expressive operations on collections. These functions often leverage closures in Swift to define and pass executable blocks of code.
Here are some commonly used higher-order functions in Swift:
map
transforms each element in a collection using a provided function or closure and returns an array containing the transformed elements.
let numbers = [1, 2, 3, 4] let squared = numbers.map { $0 * $0 } print(squared) // [1, 4, 9, 16]
filter
returns an array containing only the elements of the original array that satisfy a given condition (predicate).
let evenNumbers = numbers.filter { $0 % 2 == 0 } print(evenNumbers) // [2, 4]
reduce
combines all items in a collection to create a single new value, using a provided closure.
let sum = numbers.reduce(0, +) print(sum) // 10
In this example, 0
is the initial value, and +
is a shorthand for a closure that combines elements.
flatMap
is used to flatten a collection of collections. compactMap
transforms each element in the collection and removes any nil results.
let nestedArray = [[1, 2], [3, 4], [5, 6]] let flattened = nestedArray.flatMap { $0 } print(flattened) // [1, 2, 3, 4, 5, 6] let strings = ["1", "2", "three", "4"] let mappedNumbers = strings.compactMap { Int($0) } print(mappedNumbers) // [1, 2, 4]
forEach
applies a given closure to all elements in a collection.
numbers.forEach { print($0) }
Returns the elements of the collection, sorted using the given predicate as the comparison between elements.
let sortedNumbers = numbers.sorted(by: >) print(sortedNumbers) // [4, 3, 2, 1]
Finds the first element in the collection that satisfies a given predicate.
if let firstEven = numbers.first(where: { $0 % 2 == 0 }) { print(firstEven) // 2 }
Swift's higher-order functions, combined with closures, provide a functional approach to processing collections, allowing for concise and readable code. When used appropriately, they can result in cleaner, more understandable, and often more performant code compared to traditional loops and imperative code structures.
Swift map, filter, and reduce explained:
map
transforms each element in a collection using a provided closure. filter
selects elements based on a condition. reduce
combines all elements into a single value.let numbers = [1, 2, 3, 4, 5] let mapped = numbers.map { $0 * 2 } let filtered = numbers.filter { $0 % 2 == 0 } let sum = numbers.reduce(0, +)
Using closures with higher-order functions in Swift:
let names = ["Alice", "Bob", "Charlie"] let uppercaseNames = names.map { $0.uppercased() } let longNames = names.filter { $0.count > 5 } let concatenated = names.reduce("") { $0 + $1 }
Functional programming in Swift with higher-order functions:
let numbers = [1, 2, 3, 4, 5] let squaredSum = numbers.map { $0 * $0 }.reduce(0, +)
Swift flatMap and compactMap usage:
flatMap
transforms each element in a collection using a provided closure and flattens the result. compactMap
is similar but removes nil
values.let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let flatMapped = nestedNumbers.flatMap { $0 } let compactMapped = nestedNumbers.compactMap { $0.first }
Examples of higher-order functions in Swift:
map
, filter
, reduce
, and other higher-order functions.let numbers = [1, 2, 3, 4, 5] let squaredSum = numbers.map { $0 * $0 }.reduce(0, +) let evenSquares = numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }
Chaining higher-order functions in Swift:
let numbers = [1, 2, 3, 4, 5] let result = numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
Swift sorted and sorted(by:) higher-order functions:
sorted
arranges elements in ascending order. sorted(by:)
allows custom sorting based on a provided closure.let names = ["Alice", "Bob", "Charlie"] let sortedAlphabetically = names.sorted() let sortedByLength = names.sorted { $0.count < $1.count }
Advanced usage of higher-order functions in Swift:
struct Person { var name: String var age: Int } let people = [Person(name: "Alice", age: 25), Person(name: "Bob", age: 30)] let namesSortedByAge = people.sorted { $0.age < $1.age }.map { $0.name }
Handling optionals with higher-order functions in Swift:
map
, filter
, and compactMap
can be used with optionals to transform and filter values.let optionalNumber: Int? = 42 let squared = optionalNumber.map { $0 * $0 } let filtered = optionalNumber.filter { $0 % 2 == 0 }
Functional programming principles in Swift:
let numbers = [1, 2, 3, 4, 5] let squaredSum = numbers.map { $0 * $0 }.reduce(0, +)