The Power of Higher Order Functions in Swift

The Power of Higher Order Functions in Swift

Understanding map, filter, reduce, and other higher-order functions

Higher-order functions are functions that take other functions as parameters, return functions, or both. Learning to use these is key to unlocking expressive, declarative Swift code. This guide will explore some of the most useful higher-order functions for processing sequences like arrays.

Swift makes excellent use of higher-order functions for processing arrays, strings, ranges, and other sequences concisely. Let's examine some prominent examples.

Transforming Sequences with Map

The map function takes a sequence and returns a new sequence by applying a transform function to each element. This allows easily converting sequences from one form to another:

let names = ["Tim","Craig","Joz"]
let uppercaseNames = names.map { $0.uppercased() } 
// ["TIM","CRAIG","JOZ"]

Filtering with Filter

To filter a sequence based on criteria, use the filter function which returns only the elements for which the predicate returns true:

let numbers = [1,2,3,4,5,6]  
let evenNumbers = numbers.filter { $0 % 2 == 0 }
// [2, 4, 6]

Sequence Reduction with Reduce

Need to combine all elements into one value? Use reduce to repeatedly apply a combine operation:

let numbers = [1, 2, 3, 4, 5]  
let sum = numbers.reduce(0, { $0 + $1 })
// Sum is 15

Operating on Each Element with forEach

To perform a task with side effects on each element, forEach executes a function across them:

// using the numbers array from the Reduce example above
numbers.forEach({ print($0) })
// prints each number in the array on a new line

Flattening Mapped Sequences using FlatMap

When mapping returns nested sequences, flatMap flattens them into one:

let words = [["Hello","World"],["Swifty","Code"]] 
let flattened = words.flatMap { $0 }
// ["Hello","World","Swifty","Code"]

Removing nils with CompactMap

compactMap transforms non-nil values from a sequence, filtering out nils:

let nums = [ nil, 2, 3, nil, 5 ]
let actualNums = nums.compactMap { $0 } 
// [2, 3, 5]

Sorting Elements

The sorted function takes a sequence and returns a sorted collection:

var names = ["ZZZ","AAA","CCC"].sorted() 
// ["AAA","CCC","ZZZ"]

Summary

Higher-order functions are integral to unlocking expressive sequence processing and transformations within declarative Swift code. In each of the examples above we could have written each with standard Swift by using variables and for loops in an imperative way. But with Modern Swift influenced by Functional Programming functions like map, filter, and reduce encapsulate common data processing patterns into a simple, clean interface. Mastering their usage will greatly improve your code efficiency and elegance.

Hope this helped. Stay Swifty!

Did you find this article valuable?

Support becomingiOS by becoming a sponsor. Any amount is appreciated!