Use Collection Algorithms in Swift
Written by Team Kodeco
Collection algorithms are a set of methods that provide a functional way to perform common operations on collections such as sorting, filtering and mapping. These methods are available on all types that conform to the Sequence
protocol, which includes arrays, sets and dictionaries.
Sorting
To sort a collection, use the sorted()
method. This method returns a new collection with its elements sorted in ascending order:
let numbers = [4, 2, 6, 1, 9, 3]
let sortedNumbers = numbers.sorted()
print(sortedNumbers) // [1, 2, 3, 4, 6, 9]
Filtering
To filter a collection, use the filter()
method. This method takes a closure that returns a Boolean value indicating whether an element should be included in the filtered result:
let numbers = [4, 2, 6, 1, 9, 3]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // [4, 2, 6]
Mapping
To transform the elements of a collection, use the map()
method. This method takes a closure that applies a transformation to each element and returns the resulting collection:
let numbers = [4, 2, 6, 1, 9, 3]
let squaredNumbers = numbers.map { $0 * $0 }
print(squaredNumbers) // [16, 4, 36, 1, 81, 9]
Reducing
To reduce a collection to a single value, use the reduce()
method. This method takes a closure that combines the elements of the collection into a single value. The initial value for the reduction can be passed as an argument to the reduce()
method:
let numbers = [4, 2, 6, 1, 9, 3]
let sum = numbers.reduce(0, +)
print(sum) // 25
Chaining
These methods can be chained together to perform complex operations on a collection in a concise and readable way. For example, the following code filters an array of numbers for even values, maps them to their squares and then sums the resulting squares:
let numbers = [4, 2, 6, 1, 9, 3]
let sumOfSquaredEvenNumbers = numbers
.filter { $0 % 2 == 0 }
.map { $0 * $0 }
.reduce(0, +)
print(sumOfSquaredEvenNumbers) // 56