3 min read

Swift's Higher-Order Functions (Part1)

Swift provides several powerful higher-order functions that can significantly simplify and enhance your code. Let’s explores three of the most commonly used functions: map(), compactMap(), and flatMap(). Understanding the differences between these functions can sometimes be tricky.

map(): Transforming Elements

The map() function is one of Swift’s most versatile higher-order functions. It takes a closure and applies it to every element in a collection, returning a new collection of the same size with each element transformed.

Example: Reversing Strings

let words = ["about", "testing", "1", "100", "300"]
print("Original array:", words)

let reversedWords = words.map { String($0.reversed()) }
print("Reversed words:", reversedWords)

Output:

Original array: ["about", "testing", "1", "100", "300"]
Reversed words: ["tuoba", "gnitset", "1", "001", "003"]

In this example, map() applies the reversed() function to each string, creating a new array with reversed words.

compactMap(): Transforming and Filtering Nil Values

compactMap() combines the functionality of mapping and filtering. It transforms each element of a collection like map(), but also filters out nil values during the process. This function is particularly useful when working with optional values or when you need to clean up data that may contain nil elements.

Example: Filtering Nil Values

let mixedData: [String?] = ["about", nil, "testing", "1", nil, "100", "300", nil]
print("Original array:", mixedData)

let cleanedData = mixedData.compactMap { $0 }
print("Cleaned data:", cleanedData)

Output:

Original array: [Optional("about"), nil, Optional("testing"), Optional("1"), nil, Optional("100"), Optional("300"), nil]
Cleaned data: ["about", "testing", "1", "100", "300"]

Here, compactMap() removes all nil values and unwraps the remaining optionals, resulting in a clean array of strings.

flatMap(): Flattening Nested Collections

The flatMap() function is designed to flatten a collection of collections, combining their contents into a single-level array. This is particularly useful when dealing with nested arrays or when you need to consolidate multiple collections into one.

Example: Flattening an Array of Arrays

let nestedArrays = [["1", "2", "3"], ["a", "b", "c"], ["kyle", "harry", "tom"]]
print("Nested arrays:", nestedArrays)

let flattenedArray = nestedArrays.flatMap { $0 }
print("Flattened array:", flattenedArray)

Output:

Nested arrays: [["1", "2", "3"], ["a", "b", "c"], ["kyle", "harry", "tom"]]
Flattened array: ["1", "2", "3", "a", "b", "c", "kyle", "harry", "tom"]

In this case, flatMap() combines all the nested arrays into a single, flat array.


They may seem similar at first glance, each serves a distinct purpose: