iOS Swift reduce Method

Source: Internet
Author: User

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 from just one value, such as calculating the sum of every person's age in an ARRA Y of Person objects. Using Reduce eliminates the need for writing many loops in a program. Here's an annotated code listing, shows a loop and the equivalent usage of reduce to add together the age of Every person in an array.

There is three matching parts between the code snippets. The green box in both snippets shows how a 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 a where the sum is accumulated. in the  reduce  code, the first closure argument ($) is the running total, which starts at zero, and the Second parameter ($) References A person object in the  people  array.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.