ios – Writer extension not returning unwrapped worth


I’ve an extension which takes a writer and waits till a non-nil worth is printed earlier than taking its worth and returning it to be used as an async/await operate.

extension Writer {
  func worth() async throws -> Output {
    strive await self
      .compactMap { $0 }
      .eraseToAnyPublisher()
      .async()
  }
}

enum AsyncError: Error {
  case finishedWithoutValue
}

extension AnyPublisher {
  /// Returns the primary worth of the writer
  @discardableResult
  func async() async throws -> Output {
    strive await withCheckedThrowingContinuation { continuation in
      var cancellable: AnyCancellable?
      var finishedWithoutValue = true
      cancellable = first()
        .sink { end in
          change consequence {
          case .completed:
            if finishedWithoutValue {
              continuation.resume(throwing: AsyncError.finishedWithoutValue)
            }
          case let .failure(error):
            continuation.resume(throwing: error)
          }
          cancellable?.cancel()
        } receiveValue: { worth in
          finishedWithoutValue = false
          continuation.resume(with: .success(worth))
        }
    }
  }
}

For some cause, after I apply it to an optionally available @Printed worth, it returns an optionally available, quite than returning the unwrapped worth of it. Because it waits till a non-nil worth returns, why is not it unwrapping it? For instance, assuming foo is an optionally available printed worth:

let one = await $foo.worth() // Returns an optionally available
let two = await $foo.compactMap { $0 }.worth() // Returns a non-optional

How do I repair this?

Leave a Reply