Swift 5.9: Type of expression is ambiguous without more context

Hi all,

I have the following code which does not compile:

private func handleOnText(ws: WebSocket) -> Void {
   ws.onText { (_: WebSocket, text: String) in
      guard let payload = text.data(using: .utf8) else {
         ws.send(generateSerializationErrorMessage())
         return
      }
      
      let message: String = switch Result { try decoder.decode(ConsumerMessage.self, from: payload) } {
         case .success(let msg):
            "Success"
         case .failure():
            "Failed"
      }
      
      ws.send(message)
   }
}

The compiler complains:

Type of expression is ambiguous without more context

As you can see, I am using the new switch expression which is provided by version 5.9 and is causing the compiler error.

I will be very appreciate for the help.

Best regards

I thought you couldn’t use trailing closure syntax in an if, switch, or while like that.

2 Likes

Thanks. True.

The error message doesn't point that out, though.

The use of the trailing closure isn't the main issue here, the compiler can actually parse it (though it'll emit a warning asking you to enclose in parens), it looks like the issue is with:

case .failure():

You need to either write a pattern to match against the error associated value, or write case .failure: instead. With the latest 5.9 snapshot you'll get a marginally better error message (in that it will actually point to the problematic bit of code):

error: type '()' cannot conform to 'Error' [type_cannot_conform]
    case .failure():
          ^

But we still ought to be able to improve this, I've filed Improve enum element pattern matching diagnostics when the arity of arguments mismatch · Issue #66750 · apple/swift · GitHub to track that.