Swift Combine: Filter, the most commonly used operator

filter() operator exists in almost all programming languages for collections. What it does is same with filter() that you are familiar with. Basically whatever you provide as the body of the filter, it is going to return true or false. And the values will be either excluded or included.

Example

let numbers = (1...20) //1 to 20
.publisher
numbers.filter {
return $0 > 15
}
.sink {
print($0) //16, 17, 18, 19, 20
}

I prepared an array of numbers and made it a publisher.

With $0 > 15 , only elements that are bigger than 15 will go to the downstream of data.

Obviously, you can have the boy anywhere you like.

Right now, the body is simply saying the condition of the filter is that any number is bigger than 15 will go to the downstream (sink).

Conclusion

  • Whatever you provide as the body of the filter, it is going to return true or false. And the values will be either excluded or included.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!