2016-04-25 8 views
0

私はビューコントローラのデータを提供するプロトコルを作成しようとしています。私は、プロトコルのアプローチを取ろうとしているし、物事を柔軟にするので、ビューコントローラは任意のタイプのデータを使用して準拠することができます。プロトコル指向の汎用サービスを作成するにはどうすればいいですか?

しかし、私はエラーを取得しています:Protocol 'Serviceable' can only be used as a generic contraint because it has Self or associated type requirements

これは私がやろうとしているものです:

protocol Serviceable { 
    associatedtype DataType 
    func get(handler: ([DataType] -> Void)?) 
} 

struct PostService: Serviceable { 
    func get(handler: ([Postable] -> Void)? = nil) { 
     print("Do something...") 
    } 
} 

struct AuthorService: Serviceable { 
    func get(handler: ([Authorable] -> Void)? = nil) { 
     print("Do something...") 
    } 
} 

protocol Postable { 
    var title: String { get set } 
    var content: String { get set } 
} 

protocol ServiceControllable: class { 
    var service: Serviceable { get } // Error: Protocol 'Serviceable' can only be used as a generic contraint because it has Self or associated type requirements 
} 

extension ServiceControllable { 
    func setupDataSource() { 
     service.get { items in 
      // Do something 
     } 
    } 
} 

class MyViewController: ServiceControllable { 
    let service: Serviceable = PostService() // Error: Same as above 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     setupDataSource() 
    } 
} 

私の見解コントローラはServiceControllableを実装することができるように私はこれを設定するにはどうすればよいとテーブル、コレクションなどを読み込む汎用のsetupDataSourceにアクセスできますか?

答えて

0

このようなものが必要です。

import UIKit 

protocol Serviceable { 
    associatedtype DataType 
    func get(handler: ([DataType] -> Void)?) 
} 

struct PostService: Serviceable { 
    func get(handler: ([Postable] -> Void)? = nil) { 
     print("Do something...") 
    } 
} 

protocol Authorable {} 

struct AuthorService: Serviceable { 
    func get(handler: ([Authorable] -> Void)? = nil) { 
     print("Do something...") 
    } 
} 

protocol Postable { 
    var title: String { get set } 
    var content: String { get set } 
} 

protocol ServiceControllable: class { 

    // THIS is the way to use generic-constraint-protocols in protocols. 
    associatedtype _Serviceable: Serviceable 

    var service: _Serviceable { get } 

} 

extension ServiceControllable { 
    func setupDataSource() { 
     service.get { items in 
      // Do something 
     } 
    } 
} 

class MyViewController: UIViewController, ServiceControllable { 

    let service = PostService() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     setupDataSource() 
    } 
} 

関連ドキュメントセクション:Protocol Associated Type Declaratio

関連する問題