[英]How can I extend a Swift protocol with a default parameter when using generic types?
I have a protocol that is like我有一个类似的协议
protocol QueryProtocol {
associatedtype Data
}
protocol DataFetcher {
func fetch<Query: QueryProtocol, Output>(
query: Query,
parser: (Query.Data) -> Output,
completionHandler: (Output) -> Void
)
}
I would like to extend the protocol and provide a default value for the parser to be the identity.我想扩展协议并为解析器提供一个默认值作为身份。 So I tried
所以我试过了
extension DataFetcher {
func fetch<Query: QueryProtocol, Output>(
query: Query,
parser: (Query.Data) -> Output = { $0 }, // Cannot convert value of type 'Query.Data' to closure result type 'Output'
completionHandler: (Output) -> Void
) {
fetch(query: query, parser: parser, completionHandler: completionHandler)
}
}
But the compiler fails with Cannot convert value of type 'Query.Data' to closure result type 'Output'
但编译器失败,
Cannot convert value of type 'Query.Data' to closure result type 'Output'
Is there any way I can specify that by default Query.Data
= Output
有什么方法可以指定默认情况下
Query.Data
= Output
Is there any way I can specify that by default Query.Data
= Output
有什么方法可以指定默认情况下
Query.Data
= Output
No.不。
But, you can define an overload which works only on Query.Data
= Output
:但是,您可以定义仅适用于
Query.Data
= Output
的重载:
extension DataFetcher {
func fetch<Query: QueryProtocol, Output>(
query: Query,
completionHandler: (Output) -> Void
)
where Query.Data == Output
{
fetch(query: query, parser: { $0 }, completionHandler: completionHandler)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.