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.
Hint: This post has been updated to Swift 3
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:
let anArray = Array(1...20) var anotherArray = [Int]() for i in anArray { if i > 10 { anotherArray.append(i) } } print(anotherArray) // [11,12,13,14,15,16,17,18,19,20]
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:
let anotherArray = anArray.filter({ (a:Int) -> Bool in return a > 10 }) print(anotherArray)
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 closures, you can also do it as follows:
let anotherArray = anArray.filter ({$0 > 10}) print(anotherArray) // [11,12,13,14,15,16,17,18,19,20]
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:
let anArray = Array(1...20) let anotherArray = anArray.filter({$0 > 10}).map({$0 * 2}) print(anotherArray) // [22, 24, 26, 28, 30, 32, 34, 36, 38, 40]
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 readability.
References
Title Image: @ Joe Belanger/ shutterstock.com