swiftswift6

The thrown error from a closure can't be thrown again due to type mismatch in Swift 6


Code example:

public struct AsyncOperation<Success, Failure>: Sendable where Failure: Swift.Error {
  public typealias Operation = @Sendable () async throws(Failure) -> Success

  let operation: Operation

  public init(operation: @escaping Operation) {
    self.operation = operation
  }
}

func foo() async {
  enum InternalError: Swift.Error {
    case failed
  } 
  AsyncOperation<Int, InternalError> {
    throw InternalError.failed // <--- Invalid conversion of thrown error type 'any Error' to 'InternalError'
  }
}

Is it a bug ?


Solution

  • From the "Future Directions" section in the SE proposal, it seems like inference of typed throws in closures has not yet been implemented. For now, every closure that throw or try will be inferred as just throws, aka throws(any Error).

    For now, you need to specify the type of throws explicitly.

    AsyncOperation<Int, _> { () throws(InternalError) in
        throw .failed
    }