如何将相同的方法添加到不同的类?

时间:2016-02-08 17:24:03

标签: swift

是否可以将相同的方法添加到不同的类中?

示例:

public boolean onNavigationItemSelected(MenuItem item) {
        mClickedNavigationItem = item.getItemId();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    return true;
}

如何将相同的Foo方法添加到class FilterableTable: UITableViewController { ... } class FilterableCollection: UICollectionViewController { ... } extension FilterableTable, FilterableCollection { // I know this line is wrong func filterItems(){ print('filtered!') } }

协议允许仅声明所需的方法签名,但我需要完全相同的方法(使用正文),以避免复制粘贴......

2 个答案:

答案 0 :(得分:2)

您可以使用协议扩展来执行您需要的操作。扩展是新的,允许协议方法的默认实现。我修改了你的代码,所以它会编译。

class FilterableTable: FilterType { 
    init() {}
}
class FilterableCollection: FilterType {  
    init() {}
}

protocol FilterType {
    func filterItems()
}
extension FilterType { // I know this line is wrong
  func filterItems(){ print("filtered!") }
}

let a = FilterableTable()
a.filterItems()

let b = FilterableCollection()
b.filterItems()

查看有关协议扩展的部分。 Swift Programming Guide

答案 1 :(得分:1)

实际答案:Use the Delegates,卢克!

class FilterableTable: UITableViewController {
    var filterDelegate: FilterDelegate! 
    func viewDidLoad(){
        filterDelegate = Filter()
    }
}
class FilterableCollection: UICollectionViewController {
    var filterDelegate: FilterDelegate! 
    func viewDidLoad(){
        filterDelegate = Filter()
    }
}

protocol FilterDelegate {
    func filterItems()
}

class Filter: FilterDelegate {
    func filterItems() {
        print("Hooray!")
    }
}