简体   繁体   English

将通用 function 实现添加到基于另一个通用 function 声明的协议

[英]Add generic function implementation to protocol based on another generic function declaration

I'd like to create default implementation for convenience protocol function that just calls another protocol function, but can't figure out what's wrong with the code:我想为方便协议 function 创建默认实现,它只调用另一个协议 function,但无法弄清楚代码有什么问题:

protocol RequestManagerProtocol {
    func perform<T: Decodable>(_ request: RequestProtocol) async throws -> (T, Int)
    func perform<T: Decodable>(_ request: RequestProtocol) async throws -> T // Convenience function
}

extension RequestManagerProtocol {
    func perform<T: Decodable>(_ request: RequestProtocol) async throws -> T {
        let (obj, _) = perform<T>(request) // Error: Cannot specialize a non-generic definition
        return obj
    }
}

As the error says, you cannot specialize a function.正如错误所说,您不能专门化 function。 So you cannot do this perform<T>(request) , you have to specify the type returned to your constant:所以你不能这样做perform<T>(request) ,你必须指定返回给你的常量的类型:

 let (obj, _): (T, Int) = try await perform(request)

Also, since you're not using the returned Int , you can simply do this:此外,由于您没有使用返回的Int ,您可以简单地执行以下操作:

func perform<T: Decodable>(_ request: RequestProtocol) async throws -> T {
    return try await perform(request).0
}

First of all you have to try await the perform call.首先,您必须try await perform呼叫。

And you have to annotate the (return) type rather than specifying the type in angle brackets而且您必须注释(返回)类型,而不是在尖括号中指定类型

extension RequestManagerProtocol {
    func perform<T: Decodable>(_ request: RequestProtocol) async throws -> T {
        let (obj, _) : (T, Int) = try await perform(request)
        return obj
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM