From the course: Learning Functional Programming with Swift

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Filtering example

Filtering example - Swift Tutorial

From the course: Learning Functional Programming with Swift

Start my 1-month free trial

Filtering example

- [Instructor] So again, let's say that we have our simple array of numbers. Let numbers equal one, two, three, four, five, six, seven, eight, nine. Now, what if we want to get only the even numbers from our array? The procedural way to do this would be to create a new array. Var evenNumbers equals an empty array. And then we create a for loop to loop through each number. For number in numbers. And what we want to do is check if each number is even, and if it is, then append it to the even numbers array. The way we check if a number is even is if the number modulus two is zero. Basically, this means that if we divide the number by two, there's no remainder. It's a simple way to check and see if a number is even in code. So that will look like number modulus, which is the percent sign, two is equal to zero. And if it is, then we want to append this number to our even numbers array. evenNumbers dot append number. So now let's comment out this code and look at a functional way to do it…

Contents