[英]Extending a Protocol where Self: Generic Type in Swift (Requires Arguments In <...>)
I have a class that takes a generic class Collection: <T: Model>
( Model
is a class) and a protocol ( Resource
) that some of the subclasses of Collection
implement:我有一个类,它采用一个泛型class Collection: <T: Model>
( Model
是一个类)和一个Collection
一些子类实现的协议( Resource
):
class Collection: <T: Model> {
typealias Callback = (result: Collection <T>) -> ()
}
protocol Resource {...}
Is it possible to write a protocol extension where Self
is an instance of Collection
?是否可以编写一个协议扩展,其中Self
是Collection
一个实例?
Trying to extend the protocol with the class that takes a generic:尝试使用采用泛型的类扩展协议:
extension Resource where Self: Collection {
func fetch() {}
}
Gives:给出:
Reference to generic type 'Collection' requires arguments in <...>对泛型类型“Collection”的引用需要 <...> 中的参数
Trying to extend the class that takes a generic with the protocol:尝试使用协议扩展采用泛型的类:
extension Collection where Self: Resource {
func fetch(callback: Callback?) {}
}
Gives:给出:
'Self' is only available in a protocol or as the result of method in a class “Self”仅在协议中可用或作为类中方法的结果可用
I'm not sure how to proceed.我不知道如何继续。 The goal is for the function to only be available on instances of Collection
that conform to Resource
.目标是使函数仅在符合Resource
的Collection
实例上可用。
The problem is Collection
is a generic class so every where you declare it, you must attached the specialized type, like Collection<T>
.问题是Collection
是一个泛型类,所以在你声明它的每一个地方,你都必须附加专门的类型,比如Collection<T>
。 However extension to a protocol can't be specified with a generic type so you end up not being able to supply T
to Collection
.但是,不能使用泛型类型指定协议的扩展,因此您最终无法将T
给Collection
。
In your case though, T
is constrained to be of type Model
so why not use that in the default protocol implementation:不过,在您的情况下, T
被限制为Model
类型,所以为什么不在默认协议实现中使用它:
extension Resource where Self: Collection<Model> {
func fetch() {
// default implementation
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.