Understanding Higher-Order-Functions


Mastering Swift Higher-Order Functions: A Complete Guide

Higher-order functions are a powerful feature in Swift that enable developers to write clean, efficient, and reusable code. These functions either accept one or more functions as arguments or return a function as their result. By leveraging higher-order functions, you can simplify data manipulation without the need for additional custom functions.

Key Higher-Order Functions in Swift

  • forEach()
  • map()
  • compactMap()
  • flatMap()
  • filter()
  • reduce()
  • sort()
  • sorted()

All these functions are based on closures, but you don't need to be a closure expert to use them effectively. They enhance code readability, reduce complexity, and improve maintainability.

forEach() Function

The forEach() function works similarly to a for-in loop. It iterates through every element of a collection (such as an array) but does not return any values. Keep in mind that you cannot use break or continue within forEach().

Syntax:

func forEach(_ x: ( Self .Element ) throws -> Void ) rethrows

Example:

import Foundation
let words = [ "One", "Two", "Three", "Four", "Five" ]
words.forEach { print($0) }

Output:

One
Two
Three
Four
Five

map() Function

func forEach(_ x: ( Self .Element ) throws -> Void ) rethrows



Syntax:

func map < T >(_ transform: ( Self.Element) throws -> T) rethrows -> [T]

Example:

import Foundation
let numbers = [ 1, 2, 3, 4, 5 ]
let stringNumbers = numbers. map { String($0) }
print ( "String Numbers: \(stringNumbers) " )

Output:

String Numbers: ["1", "2", "3", "4", "5"]

compactMap() Function

compactMap() filters out nil values from a collection and returns an array containing only valid elements.

Example:

// Filter valid numbers from mixed data
import Foundation
let mixedData = ["3", "x", "7", nil, "12"]
let validNumbers = mixedData.compactMap { Int($0 ?? "") }
print("Valid Numbers: \(validNumbers)")

Output:

Valid Numbers: [3, 7, 12]

flatMap() Function

The flatMap() function flattens nested collections into a single collection, making it easier to process multi-dimensional arrays.

Syntax:

// Swift flatMap function
func flatMap(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult: Sequence

Example:

// Swift flatMap example
import Foundation
let nestedArrays = [[ 1, 2 ], [ 3, 4], [ 5, 6 ]]
let flatArray = nestedArrays.flatMap { $0 }
print( "Flattened Array: \(flatArray) " )

Output:

Flattened Array: [1, 2, 3, 4, 5, 6]

filter() Function

The filter() function returns a new collection containing only elements that meet a specified condition.

Syntax:

// Swift filter function
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]

Example:

// Filter positive numbers from an array
import Foundation
let numbers = [-10, 5, -3, 8, 0, 12]
let positiveNumbers = numbers.filter { $0 > 0 }
print("Positive Numbers: \(positiveNumbers)")

Output:

Positive Numbers: [5, 8, 12]

reduce() Function

The reduce() function combines all elements in a collection into a single computed result.

Syntax:

// Reduce function signature in Swift
func reduce<Result>( _ initialResult: Result, _ nextPartialResult: (Result, Self.Element) throws -> Result ) rethrows -> Result

Example:

// Calculate the sum of an array using reduce
import Foundation
let numbers = [1, 2, 3, 4]
let sum = numbers.reduce(0) { $0 + $1 }
print("Sum: \(sum)")

Output:

Sum: 10

sort() Function

The sort() function sorts elements of a collection in ascending order (by default) or based on a custom condition.

Example:

// Sort an array of numbers in ascending order
import Foundation
var numbers = [5, 2, 8, 3]
numbers.sort ()
print("Sorted Numbers: \(numbers)")

Output:

Sorted Numbers: [2, 3, 5, 8]

sorted() Function

The sorted() function returns a new sorted collection without modifying the original array.

Example:

// Sort an array of numbers in ascending order
import Foundation
var numbers = [5, 2, 8, 3]
let sortedArray = numbers.sorted ()
print("Sorted Numbers: \(numbers)")

Output:

Sorted Numbers: [1, 4, 7, 9]