For-in-loops are often used to iterate through an array of objects, modifying another object with each iteration. For example, looping through an array of numbers in order to create a new array of numbers formatted as strings:
With Swift, iOS and Mac developers have
reduce methods on arrays. In my experience, these methods can replace almost all uses of for-in-loops, and are more clear and concise.
map method takes a function (
transform), and returns an array containing the results of calling
transform on each element in the array. The example above could be written like this:
filter method takes a function (
includeElement) which, given an element in the array, returns a
Bool indicating whether the element should be included in the resulting array. For example, removing all the odd numbers from the
numbers array could be done like this:
reduce method reduces an array into a single value. It takes two parameters: a starting value, and a function which takes a running total and an element of the array as parameters, and returns a new running total. For example, getting the sum of all the numbers in an array could be done like this:
These three methods can be very powerful, especially when they are chained. For example, given an array of numbers, we can filter out all odd numbers, map the remaining numbers into strings using
NSNumberFormatter, and reduce those strings into one string, with a formatted number on each line:
All the examples from this article can be downloaded as a playground from GitHub.
Check out more of our posts about Swift.