filter

Swift: filter

Swift provides you some handy functions like filter and map for manipulating arrays. In this post we will take a look at filter and how you can combine it with map.

So, let’s imagine you have an array and you want to to create a new array that has all elements of the array that are bigger than 10. You can do this by using a for loop:

That works great, but it’s also a lot of code.

Filter

But there is a shorter way by using the function filter that is available on every array:

The function takes a closure as an argument. The closure itself gets a value of the array type as an argument and returns a bool. The closure will be executed on every value of the array and within the closure you decide whether the value should be contained in the new array or not.

By using one of Swift’s short cuts to write a closure, you can also do it as follows:

Compared to the first version, this is very short.

Combined with map

map is another interesting function that is available on an array. It also takes a closure and returns a transformed element. So now we first filter the array for every value that is greater than ten, and then we will double that value:
Fore more details about map, take a look at one of my previous blog posts.

However, you should only do it this way if the terms are not too complicated. If they are, it will become very difficult to read. Generally speaking, you should always write more code, if this leads to more readable code.

References

Title Image: @ Joe Belanger/ shutterstock.com

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon