2015-09-15 145 views
4

我一直在玩協議擴展,我有一個問題。也許我想達到的目標是無法完成的。我有這樣的遊樂場:Swift 2:UITableViewDataSource協議擴展

//: Playground - noun: a place where people can play 

import UIKit 

protocol ArrayContainer { 
    typealias T 
    var array: [T] { get } 
} 

class MyViewController: UIViewController, ArrayContainer, UITableViewDataSource { 
    typealias T = String 
    var array = ["I am", "an Array"] 
} 

extension UITableViewDataSource where Self: ArrayContainer { 

    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return array.count 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     // Whatever 
     return UITableViewCell() 
    } 
} 

這是我有什麼,我想:

  • 我有一個協議ArrayContainer,只是有一個typealias以及包含該typealias類型的對象數組
  • 我有一個UITableViewDataSource的協議擴展當類符合ArrayController協議時使用。這只是返回數組的行數作爲行數。 cellForRowAtIndexPath方法沒有很好地實現,但它不是問題。
  • 我有一個叫做MyViewControllerUIViewController子類,它實現了兩種協議。

的問題是,編譯器會抱怨,因爲MyViewController不UITableViewDataSource符合,但是,據我所知,這應該由UITableViewDataSource延伸覆蓋。我在這裏錯過了什麼嗎?或者也許Objective-C協議不能被擴展?

+1

問題可能與http://stackoverflow.com/questions/32542362/swift-2-0-uitextfielddelegate-protocol-extension-not-working – ABakerSmith

+0

我敢肯定,這個問題是因爲協議無法通過Objective-C訪問擴展,並且「UITableViewDataSource」實現需要是ObjC可訪問的。 – Logan

+0

是的,我認爲這是問題,但它在任何地方記錄? – manueGE

回答

3

我知道這件事有點遲,你甚至可能沒有在尋找這個答案,但我剛剛遇到了這個確切的問題,需要一個真實的世界「解決方案」。您可以在類中實現UITableViewDataSource方法,然後立即將工作交給協議擴展,如下例所示。如果swift進行了不再需要的改進,則可以很簡單地回到原始文章中的代碼。

//: Playground - noun: a place where people can play 

import UIKit 

protocol ArrayContainer { 
    associatedtype T 
    var array: [T] { get } 
} 

class MyViewController: UIViewController, ArrayContainer, UITableViewDataSource { 
    typealias T = String 
    var array = ["I am", "an Array"] 

    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return self.internal_numberOfSectionsInTableView(tableView) 
    } 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return self.internal_tableView(tableView, numberOfRowsInSection: section) 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     return self.internal_tableView(tableView, cellForRowAtIndexPath: indexPath) 
    } 
} 

extension UITableViewDataSource where Self: ArrayContainer { 

    func internal_numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

    func internal_tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return array.count 
    } 

    func internal_tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     // Whatever 
     return UITableViewCell() 
    } 
} 
+1

這不是我所期望的,但我認爲這是目前唯一的選擇。 – manueGE