Leave a rating/review
You’ve learned all about Filtering Operators - so now it’s time for a challenge. For this challenge: create a publisher that emits a collection of numbers from 1 to 100.
Use filtering operators to: skip the first 50 values emitted by the publisher; take the next 20 values from the publisher; only take even numbers. You should get the following numbers, one per line
Pause the video, try coming up with a solution, and when you’re ready resume the video and I’ll walk you through my solution.
Did you get the right sequence of numbers? Let’s look at a solution. First, making the publisher can be done just like the other examples in this part of the course, using the colletion’s built in publisher
let numbers = (1...100).publisher
To ignore the first 50 values from the publisher, use dropFirst
numbers
.dropFirst(50)
Use the prefix operator to grab the next 20 values, and be done
.prefix(20)
Next, filter out the incoming values and accept only the ones that are even - or divisible by 2.
.filter({ $0 % 2 == 0})
Finally, add the usual sink and store calls at the end
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
Run the playground and check the expected values - 52 through 70, just the even numbers. If you got this, great job!