简体   繁体   中英

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> {
  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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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