* 短縮版 *
クラス (拡張機能) を汎用プロトコル関数に適合させるにはどうすればよいですか?
※ロングバージョン※
これは、ページ分割されたコレクションをサポートするためのデータ構造の小さな部分です。
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 typealias の有効な型を関数に返させることができますか?
*ボーナス*
50 報奨金に値するボーナス質問(回答が 1 行より長い場合は、新しい質問を開きます): 最初のコード スニペットを参照するPagedCollection
- 各 Page 実装には常に Pageable プロトコル オブジェクト タイプの既知の実装があることを前提としています。
- 宣言を避ける方法はあり
ItemType:Pageable
ますか? または、少なくともwhere
句でそれを強制しますか?