* Short version *
How can I conform a class (extension) to a generic protocol function?
* Long version *
This is a small part of a data structure to support a paginated collection,
protocol Pageable {
//an object whose can be in a collection
}
protocol Page{ //a page of a collection that can be paginated
associatedtype PageItemType
func itemAt<PageItemType:Pageable>(index: Int) -> PageItemType
}
//Bonus question
//class PagedCollection<PageType:Page, ItemType:Pageable> {
//...
//}
Here is the implementation of the protocols with a "real" case:
class Person : Pageable{}
class People {
var people: [Person]?
}
//Mark: - Page
extension People: Page{ /*** error 1 ***/
typealias PageItemType = Person
func itemAt(index: Int) -> Person{
let person : Person = self.people![index]
return person
}
}
Obtaining the following error (1):
Type 'People' does not conform to protocol 'Page'
Protocol requires nested type 'PageItemType'
I also tried making it explicit but i just got a different error:
//Mark: - Page
extension People: Page{
typealias PageItemType = Person
func itemAt<PageItemType:Pageable>(index: Int) -> PageItemType{
let person : Person = self.people![index]
return person /*** error 2 ***/
}
}
Obtaining the following error (2):
Cannot convert return expression of type 'Person' to return type 'PageItemType'
So: *How can i let itemAt
function return a valid type for the PageItemType typealias?
* Bonus *
Bonus question worth a 50 bounty (if answer is longer than a row i'll open a new question):
Referring to the first code snippet PagedCollection
- given that each Page implementation has always a known implementation of Pageable protocol objet type
- is there a way to avoid declaring
ItemType:Pageable
? Or at least enforce it with awhere
clause?