由于 Swift 6 中类型不匹配,闭包抛出的错误无法再次抛出

问题描述 投票:0回答:1

代码示例:

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'
  }
}

这是一个错误吗?

ios swift swift6
1个回答
0
投票

从SE提案中的“未来方向”部分来看,闭包中类型化抛出的推理似乎尚未实现。每个

throw
try
的闭包都会被推断为
throws
,又名
throws(any Error)

目前,您需要明确指定

throws
的类型。

AsyncOperation<Int, _> { () throws(InternalError) in
    throw InternalError.failed
}
© www.soinside.com 2019 - 2024. All rights reserved.