Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 InternalError.failed
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading