KPM
KPM

Reputation: 10608

How to convert an atypical completion handler to Swift Concurrency

I have in my code some asynchronous method written with a completion handler, and I want to convert it to the new Swift Concurrency syntax.

Usually this is simply a matter of wrapping the call in withCheckedThrowingContinuation and calling either resume(throwing:) or resume(returning:) instead of, respectively completion(nil, error) or completion(value, nil).

However I have in my code a method that may call the completion handler with a value AND an error (the use case is: outdated cache, but use the value if network is unreachable), aka completion(value, CacheError.outdatedCache).

What approach may I use to convert this to a throwing async method?

Upvotes: 0

Views: 154

Answers (1)

Rob
Rob

Reputation: 437382

There are many alternatives. Here are a few:

  1. You could have a non-throwing rendition that returns a Response:

    enum Response<Value, Failure: Error> {
        case success(Value)
        case failure(Failure)
        case failureWithCachedValue(Failure, Value)
    }
    
  2. You could have non-throwing rendition that returns a tuple of (Foo?, Error?).

Upvotes: 2

Related Questions