JuniorCodeCommonNot answered yet
Build a small pipeline with map, filter, compactMap, and scan, and say what each emits
Starting from a publisher of String inputs, build a chain that:
- keeps only numeric strings and converts them to
Int(drop the rest), - passes through only even numbers,
- emits a running sum.
func runningEvenSum(_ input: AnyPublisher<String, Never>) -> AnyPublisher<Int, Never> {
input
// your code here — map / filter / compactMap / scan
}
Write the implementation and state what each operator emits.
map transforms each element one-to-one and never drops. compactMap maps then drops any nil, so non-numeric strings vanish. filter forwards only elements passing a predicate. scan keeps an accumulator and emits the running total after every element.
- ✗Confusing
compactMap(dropsnil) withmap(transforms 1:1) - ✗Thinking
scanemits only once at completion, not per element - ✗Assuming
filtertransforms values rather than passing them through
- →How does
scandiffer fromreducein what it emits? - →When would you reach for
compactMapovermapplusfilter?
func runningEvenSum(_ input: AnyPublisher<String, Never>) -> AnyPublisher<Int, Never> {
input
.compactMap { Int($0) } // String -> Int?, drops non-numeric
.filter { $0 % 2 == 0 } // keeps even numbers only
.scan(0, +) // running sum of what passed
.eraseToAnyPublisher()
}
compactMap maps and unwraps in one step, dropping any nil; filter forwards only elements passing its predicate; scan carries an accumulator and emits it after every element. map (not needed here) would transform one-to-one without ever dropping.