Can someone tell me, what's wrong in my code or how i can decompose this method to debug, i have latest xCode v.14.1 (14B47b), somehow it compiles on v.13.4.1 -_-
extension WebSocket {
@available(macOS 10.15, *) func connectUntilBody(write: String? = nil ) async throws -> Data? {
try await withCheckedThrowingContinuation { continuation in // <-- Type of expression is ambiguous without more context
var result: Result<Data?, Error> = .success(nil)
onEvent = { [weak self] event in
if let body = event.body {
result = .success(body)
let group = DispatchGroup()
if let write = write {
group.enter()
self?.write(string: write) {
group.leave()
}
}
group.notify(queue: .main) {
self?.disconnect()
}
} else if case let .error(error) = event {
error.flatMap { result = .failure($0) }
self?.disconnect()
} else if case .cancelled = event {
continuation.resume(with: result)
}
}
connect()
}
}
}
CodePudding user response:
There are some major issues:
- If you mark the function as
throws
you have toresume
the error. - You must
resume
the data in the happy path. - The
DispatchGroup
makes no sense. As thecontinuation
isasync
anyway you canresume
in thewrite
closure. - You must also ensure that
resume
is called only once.
To answer the question:
If the compiler cannot infer the type of the continuation
you have to annotate it. In your case
(continuation: Result<Data?,Error>)in
But you can also call continuation.resume(returning:)
to return the data, and continuation.resume(throwing:)
to return the error. See issue 1).
You should also return non-optional Data
otherwise an error. By the way that's the goal of the Result
type.