Home > Software engineering >  Type of expression is ambiguous without more context xCode 14.1
Type of expression is ambiguous without more context xCode 14.1

Time:11-24

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:

  1. If you mark the function as throws you have to resume the error.
  2. You must resume the data in the happy path.
  3. The DispatchGroup makes no sense. As the continuation is async anyway you can resume in the write closure.
  4. 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.

  • Related