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
1
to6
. - The
compactMap
operator transforms the emitted value to the corresponding value from thedictionary
. - The operator filters out
nil
values. - The
sink
subscriber prints the non-nil values.
The output of the above code will be:
A
B
D
E