2015-09-15 146 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