swift 在withCheckedThrowingContinuation中使用自定义错误

nxowjjhe  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(148)

我无法使Xcode接受以下代码。

enum FooError : Error {}

class FooTest {
    func slowMethod() async throws {
        try await withCheckedThrowingContinuation { (c: CheckedContinuation<Void, FooError>) -> Void in
        }
    }
}

获取以下编译错误:Cannot convert value of type '(CheckedContinuation<Void, FooError>) -> Void' to expected argument type '(CheckedContinuation<Void, any Error>) -> Void'. Arguments to generic parameter 'E' ('any Error' and 'FooError') are expected to be equal
withCheckedThrowingContinuation是否可以接受自定义错误?

编辑

下面的评论,这也不起作用:

enum FooError : Error {}

class FooTest {
    func slowMethod() async throws {
        try await withCheckedThrowingContinuation { (c: CheckedContinuation<Void, Error>) -> Void in
            c.resume(throwing: FooError)
        }
    }
}

给出的误差为:Argument type 'FooError.Type' does not conform to expected type 'Error'

swvgeqrz

swvgeqrz1#

我认为你误解了一些基本的东西。

enum FooError : Error {} // This on its own says that any `value` of `Type` FooError will conform to Error

FooError本身是Type,而不是value
现在要获得value,在处理enum时需要case

enum FooError : Error {
    case someValueHere //This is a value
}

最后的代码看起来像这样。

actor FooTest {
    func slowMethod() async throws  {
        try await withUnsafeThrowingContinuation({ (c: UnsafeContinuation<Void, Error>) in
            c.resume(throwing: FooError.someValueHere)
        })
    }
}

注意,由于返回值是Void,因此我使用的是withUnsafeThrowingContinuation
withCheckedThrowingContinuation希望您调用c.resume(/* some return value */)
如果使用LocalizedError,则可以提取辅助Error

enum FooError : LocalizedError {
    case someValueHere //This is a value
    case bar(_ innerError: Error)
    
    var errorDescription: String?{
        switch self {
        case .bar(let error):
            let nsError = error as NSError
            return nsError.localizedDescription
        default:
            return "\(self)".localizedCapitalized
        }
    }
    var failureReason: String?{
        switch self {
        case .bar(let error):
            let nsError = error as NSError
            return nsError.localizedFailureReason
        default:
            return nil
        }
    }
    var helpAnchor: String? {
        switch self {
        case .bar(let error):
            let nsError = error as NSError
            return nsError.helpAnchor
        default:
            return nil
        }
    }
    var recoverySuggestion: String? {
        switch self {
        case .bar(let error):
            let nsError = error as NSError
            return nsError.localizedRecoverySuggestion
        default:
            return nil
        }
    }

}

相关问题