Search code examples
swiftunit-testingswift4rx-swiftrx-blocking

iOS RxSwift - How to unwrap an `Optional<Optional<T>>` or `T??`?


I'm using the logic below to check the state of my subject using RxBlocking. I'm getting a weird value of Int?? out of try? subject.verifier.toBlocking().first().

The syntax below pleases the compiler but makes my eyes bleed.

How do I get an unwrapped value out of RXBlocking expectation?

func checkSubjectState() -> Int
    {
      let updatedChecksum = try? subject.verifier.toBlocking().first() ?? 0
      return updatedChecksum ?? 0
    }

let expectedCheckSum = checkSubjectState()
expect(expectedCheckSum).to(equal(knownValue))

Solution

  • Here's an answer that doesn't require you to define any of your own functions:

    return (try? subject.verifier.toBlocking().first()).flatMap { $0 } ?? 0