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
.publishernumbers.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.