Use the compactMap operator in Combine to publish non-nil results of a transformation.
import Combine
let dictionary = [1: "A", 2: "B", 4: "D", 5: "E"]
(1...6).publisher
.compactMap { dictionary[$0] }
.sink { print($0) }
In the above code:
- The publisher emits values from
1to6. - The
compactMapoperator transforms the emitted value to the corresponding value from thedictionary. - The operator filters out
nilvalues. - The
sinksubscriber prints the non-nil values.
The output of the above code will be:
A
B
D
E