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?
There are many alternatives. Here are a few:
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) }
You could have non-throwing rendition that returns a tuple of (Foo?, Error?)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.