* 精简版 *
如何使类(扩展)符合通用协议函数?
* 长版 *
这是支持分页集合的数据结构的一小部分,
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> {
//...
//}
这是具有“真实”案例的协议的实现:
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
}
}
得到如下错误(1):
类型“人”不符合协议“页面”
协议需要嵌套类型“PageItemType”
我也试过让它明确,但我得到了一个不同的错误:
//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 ***/
}
}
得到如下错误(2):
无法将“Person”类型的返回表达式转换为“PageItemType”类型
所以:*如何让itemAt
函数返回 PageItemType 类型别名的有效类型?
* 奖金 *
价值 50 的奖励问题(如果答案超过一行,我将打开一个新问题):参考第一个代码片段PagedCollection
- 假设每个 Page 实现总是有一个已知的 Pageable 协议对象类型的实现
- 有没有办法避免声明
ItemType:Pageable
?或者至少用一个where
条款来强制执行它?