Understanding Swift’s reduce Method

Swift’s API includes many functions and instance methods that reflect its functional programming heritage. A prime example is called reduce.  You can reduce a collection of values down to just one value, such as calculating the sum of every person’s age in an array of Person objects. Using reduce eliminates the need for writing many loops in a program. Here is an annotated code listing that shows a loop and the equivalent usage of reduce to add together the age of every person in an array.

There are three matching parts between the two code snippets. The green box in both snippets shows how an initial value is defined, in this case zero. The yellow underline shows how each approach iterates the array of Person objects. The red underline is where the sum is accumulated. In the reduce code, the first closure argument ($0) is the running total, which starts at zero, and the second parameter ($1) references a Person object in the people array.

This entry was posted in Swift and tagged , . Bookmark the permalink.

7 Responses to Understanding Swift’s reduce Method

  1. Lord Anubis says:

    Ugly, you must know it, otherwise you can’t see how it works.

  2. I also don’t like this or any other kinds of cryptic code. IMHO code doesn’t need to be shortened; it has to be clear. One of the reasons I also don’t use LINQ in .NET.

  3. Jordan Day says:

    Marcus and Lord Anubis’ comments intend* their comments to be an example of the division between imperative and functional programmers.

    Imperative programmer: “I know what I want to do, and I want to tell the computer how to do it.”
    Functional programmer: “I know what I want to do, and I’ll let the computer figure out how to do it.”

    Both approaches have their benefits and drawbacks. I think for something like Josh’s example, though, it makes lots of sense to take the functional approach.

    * – I say “intend”, because their comments are very clearly actually “This is unfamiliar to me, therefore it’s unclear/wrong/bad/dumb!” Anyone familiar with reduce (“aggregate” in linq, I believe) is able to read that code just as “clearly” as the for loop.

    • Josh Smith says:

      Well put, Jordan. It’s imperative to keep an open mind when learning about functional programming. 😉

  4. JordanN (@BackBaySoxFan) says:

    Fully agree with Jordan D.

    Code clarity is achieved when code is direct and clear about its intention. The assumption should always be that the audience has a reasonable mastery of programming language and idiom. It is incumbent upon no one to write code in a manner considered clear by the village idiot.

Comments are closed.