首页 > 代码库 > ios swift reduce Method

ios swift 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.