We show some examples of how Swift's built-in reduce function can be used to work with arrays in a cleaner way.
- [Instructor] So let's go over…a few examples of how reduce is used.…If we start off again with our array of numbers,…let numbers equals one, two, three,…four, five, six, seven, eight, nine.…If we want to calculate the sum…of all the numbers in our array,…the procedural way of doing this is like this.…We create a variable to hold our sum,…var sum equals zero,…and then we loop through each of our numbers,…for number in numbers,…and we add each of those numbers…to our sum variable, sum plus equals number.…
The way reduce works is a little different…from the other functions that we've seen already.…In the other functions we've seen,…the function that we pass in needs only one argument,…which represents the element of the array…that we're currently working on.…With reduce however, the function we pass in…needs two arguments.…So let's create a function called reduceSum.…Function, reduceSum.…And this function will take two arguments.…The first argument will represent the sum…that we've accumulated so far.…We'll just call it sum, and that will be an integer.…
- What is functional programming?
- Keeping functions and data separate
- First-class functions
- Working with arrays functionally
- Filtering and reducing
- Partial-application and recursion
Skill Level Intermediate
Swift 4: Protocol-Oriented Programmingwith Károly Nyisztor1h 44m Intermediate
Swift: Delegations and Data Sourceswith Steven Lipton1h 6m Intermediate
Swift: Writing Reusable Frameworkswith David Okun1h 49m Intermediate
1. What Is Functional Programming?
2. First-Class Functions
3. Array Functions
4. Advanced Functional Concepts
Next steps1m 1s
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.