ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Combine Pipeline for Data Transformation and Filtering

Swift

Goal -- WPM

Ready
Exercise Algorithm Area
1import Combine
2import Foundation
3
4// Represents a publisher that emits integers.
5// We'll use a simple PassthroughSubject for demonstration.
6class IntegerPublisher {
7let subject = PassthroughSubject<Int, Never>()
8
9func send(_ value: Int) {
10subject.send(value)
11}
12
13func finish()
14{
15subject.send(completion: .finished)
16}
17}
18
19// Creates a Combine pipeline to process a stream of integers.
20// Filters out even numbers, squares odd numbers, and publishes the results.
21func createProcessedIntegerPipeline() -> AnyPublisher<Int, Never> {
22// Create a publisher from the IntegerPublisher's subject.
23let publisher = IntegerPublisher().subject
24
25return publisher
26.filter { $0 % 2 != 0 } // Keep only odd numbers.
27.map { $0 * $0 } // Square the odd numbers.
28.eraseToAnyPublisher() // Erase the concrete type for a generic publisher.
29}
30
31// Example Usage:
32// var cancellables = Set<AnyCancellable>()
33//
34// let processedPipeline = createProcessedIntegerPipeline()
35//
36// // Subscribe to the pipeline.
37// processedPipeline
38// .sink(receiveCompletion: { completion in
39// print("Pipeline completed: \(completion)")
40// }, receiveValue: { value in
41// print("Received processed value: \(value)")
42// })
43// .store(in: &cancellables)
44//
45// // Simulate sending data through the pipeline.
46// let publisherInstance = IntegerPublisher()
47// publisherInstance.send(1)
48// publisherInstance.send(2)
49// publisherInstance.send(3)
50// publisherInstance.send(4)
51// publisherInstance.send(5)
52// publisherInstance.finish()
Algorithm description viewbox

Combine Pipeline for Data Transformation and Filtering

Algorithm description:

This Swift code defines a Combine pipeline that processes a stream of integers. It first filters out all even numbers, then squares the remaining odd numbers. The transformed values are then published to any subscribers. This pattern is common for data processing where you need to react to incoming data, transform it, and potentially filter out irrelevant items before further action.

Algorithm explanation:

The `createProcessedIntegerPipeline` function sets up a reactive data processing pipeline using Apple's Combine framework. It starts with a `PassthroughSubject` which acts as the source of integers. The pipeline then applies a sequence of operators: `.filter { $0 % 2 != 0 }` keeps only the odd numbers, and `.map { $0 * $0 }` squares each of these odd numbers. Finally, `.eraseToAnyPublisher()` is used to hide the specific publisher type, returning a generic `AnyPublisher`. Subscribers can then connect to this publisher using `.sink` to receive the processed values. The pipeline is designed to be error-free (`Never` error type) for this specific example, simplifying error handling. The time complexity is effectively O(1) per element processed by the pipeline, as each operation is a constant-time transformation or filter. The space complexity is O(1) for the pipeline itself, plus any storage needed by subscribers.

Pseudocode:

class IntegerPublisher:
  create a PassthroughSubject for Integers (no errors)
  function send(value):
    send value to subject
  function finish():
    send completion to subject

function createProcessedIntegerPipeline():
  get the subject from an IntegerPublisher instance
  return publisher:
    filter for odd numbers (number % 2 != 0)
    map to square the number (number * number)
    erase to AnyPublisher