代码示例:
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'
}
}
这是一个错误吗?
从SE提案中的“未来方向”部分来看,闭包中类型化抛出的推理似乎尚未实现。每个
throw
或try
的闭包都会被推断为throws
,又名throws(any Error)
。
目前,您需要明确指定
throws
的类型。
AsyncOperation<Int, _> { () throws(InternalError) in
throw InternalError.failed
}