From the course: Learning Functional Programming with Swift
Unlock the full course today
Join today to access over 22,400 courses taught by industry experts or purchase this course individually.
Reducing example - Swift Tutorial
From the course: Learning Functional Programming with Swift
Reducing example
- [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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.