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> {
typealias Callback = (result: Collection <T>) -> ()
}
protocol Resource {...}
Is it possible to write a protocol extension where Self
is an instance of 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 <...>
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
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
.
The problem is Collection
is a generic class so every where you declare it, you must attached the specialized type, like 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
.
In your case though, T
is constrained to be of type Model
so why not use that in the default protocol implementation:
extension Resource where Self: Collection<Model> {
func fetch() {
// default implementation
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments