Deal with Optional Type in Swift Combine

Mykola Fiantsev
2 min readSep 20, 2019
image from: https://www.avanderlee.com/swift/combine/

I like the power of strong typing which Swift language provides for us as the developers. Bring it together with a functional reactive programming approach helps me to build responsive iOS applications for different business needs. RxSwift used to help me with it, but after Combine was introduced I decided to dig deep into it and write a new pet project within it.

Combine is a newborn baby and I miss some tools I used to have in RxSwift. What if we have an events stream which can throw ‘nil’ values:

But on the other hand, we won’t deal with ‘nil’ in some method: func doSomething(_ value: Int) Of course, we can use filter or flatMap or whatever:.filter { $0 != nil } But what type will we get downstream? Anyway, we should deal with an Optional Type. The knowledge of "not possible nil in there" forces us to use some technics, which I don't really like in my code.

The strong RxSwift Community gives us an extension RxOptional, which allows us to filter ‘nil’ values and unwrapped type in the downstream. Inspired by this extension I wrote the similar for Combine and made it available via Swift Package.

It’s simple but allows me to avoid copy-paste across all my projects. It’s my first article on Medium, but I think that it can be useful for Combine’s newcomers. Here is my CombineOptional package. Welcome to join if you need something like that.

And when I have finished this article some guy reminded me about compactMap… 🤦‍♂️😊

https://github.com/bigMOTOR/CombineOptional

--

--