4

I'm trying to do something like this:

//: Playground 

import Cocoa

protocol FeedItem {
    var foo: Int {get}
}

protocol FeedFetchRequest {
    func fetchItems<T:FeedItem>(success success: ([T])->())
}

class MyFeedController {
    func fetchItems<T:FeedFetchRequest, G:FeedItem>(request: T) {
        request.fetchItems{ (items: [G]) -> () in
            //do stuff
        }
    }
}

However, I get the error Generic Parameter 'G' is not used in function signature. Adding G as an optional return value enables me to use it internally, but this seems hacky, as I don't want to return anything.

rob
  • 4,069
  • 3
  • 34
  • 41
  • 1
    Maybe `func fetchItems(request: T, ofType: G.Type) {...}` ? Anyways you have to pass the G type somehow to the function – Soheil Jadidian Sep 04 '15 at 23:09
  • 1
    Or, take a look at this http://stackoverflow.com/questions/24469913/how-to-create-generic-protocols-in-swift-ios you could use `typealias` to make `FeedFetchRequest` a generic protocol, and then you won't need G in `fetchItems` signature – Soheil Jadidian Sep 04 '15 at 23:21

1 Answers1

3

The error occurs because the compiler cannot infer the type of G since you cannot provide any details as parameter or return type.

In this example you could help the compiler by specifying the type as parameter:

func fetchItems<T:FeedFetchRequest, G:FeedItem>(request: T, type: G.Type)

Another way to solve this problem is to make the protocol requirement a non generic function which takes a heterogeneous array of FeedItem if this fits in your project:

protocol FeedFetchRequest {
    func fetchItems(success success: [FeedItem]->())
}

class MyFeedController {
    func fetchItems<T:FeedFetchRequest>(request: T) {
        request.fetchItems{ (items: [FeedItem]) -> () in
            //do stuff
        }
    }
}
Qbyte
  • 12,753
  • 4
  • 41
  • 57