What are higher order functions in swift ?

By | February 28, 2024


Higher-order functions in Swift are functions that take other functions as parameters or return functions as output. They enable a functional programming style by allowing you to compose functions, pass behavior as arguments, and manipulate collections with concise and expressive code.

Here are some common higher-order functions in Swift with examples:

map(_:):

  • Applies a transformation to each element of a collection and returns an array containing the transformed elements.
let numbers = [1, 2, 3, 4, 5]
let squaredNumbers = numbers.map { $0 * $0 }
// squaredNumbers: [1, 4, 9, 16, 25]

filter(_:):

  • Selects elements from a collection that satisfy a given predicate and returns a new array containing only the matching elements.
let numbers = [1, 2, 3, 4, 5]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
// evenNumbers: [2, 4]

reduce(_:combine:):

  • Combines all elements of a collection into a single value using a closure.
let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(0, +)
// sum: 15

sorted(by:):

  • Returns a new array containing the elements of the collection, sorted using a given predicate.
let names = ["John", "Alice", "Bob", "Eve"]
let sortedNames = names.sorted(by: <)
// sortedNames: ["Alice", "Bob", "Eve", "John"]

flatMap(_:):

  • Transforms each element of a collection and flattens the resulting sequence into a single array.
let words = ["apple", "banana", "cherry"]
let characters = words.flatMap { $0.uppercased() }
// characters: ["A", "P", "P", "L", "E", "B", "A", "N", "A", "N", "A", "C", "H", "E", "R", "R", "Y"]

forEach(_:):

  • Performs an operation on each element of a collection without returning a new array.
let numbers = [1, 2, 3, 4, 5]
numbers.forEach { print($0) }
// Output: 1, 2, 3, 4, 5 (printed on separate lines)

compactMap(_:):

  • Returns an array containing the non-nil results of calling a transformation on each element of the collection.
let optionalNumbers: [Int?] = [1, 2, nil, 4, nil, 6]
let validNumbers = optionalNumbers.compactMap { $0 }
// validNumbers: [1, 2, 4, 6]

These are just a few examples of higher-order functions available in Swift. They provide powerful tools for manipulating collections and performing common operations in a functional programming style.

Leave a Reply

Your email address will not be published. Required fields are marked *