如何使Swift协议符合特定类的类?

时间:2018-04-30 01:41:27

标签: ios swift class protocols

我在Swift中写了一个协议:

protocol FooDelegate{
    titleImage:UIImage? {get}
}

我想确保符合它的类必须是UITableViewController类型。

换句话说:

// ViewController conform FooDelegate is OK,Because ViewController 
// is inherit from UITableViewController!
class ViewController:UITableViewController,FooDelegate /* compile ok */{

}

// OtherVC is failed to conform FooDelegate,Because it is not inherit
// from UITableViewController.
class OtherVC:UIViewController,FooDelegate /* will compile error */{

}

怎么做?

我将FooDelegate的定义更改为:

protocol FooDelegate where Self:UITableViewController {
    var titleImage:UIImage? {get}
}

但它似乎不起作用。

* FIX PART * : 使用Self:UITableViewController没关系!!!

但是当编写时,我写下面的内容是错误的:

class StubClass{
    var delegate:FooDelegate!

    func invoke(){
        let idxSet = ...
        delegate.tableView.reloadSections(idxSet, with: .none) //Error:Value of type 'FooDelegate' has no member 'tableView'
    }
}

请查看上面的错误行。委托中是否有任何tableView属性?委托符合FooDelegate,而FooDelegate使Self:UITableViewController和UITableViewController必须具有tableView属性?? !!

这里有什么问题?谢谢:))

2 个答案:

答案 0 :(得分:4)

由于tableView属性对协议声明不可见,您只需在协议中添加tableView属性即可。像这样:

@objc protocol FooDelegate where Self: UITableViewController {
    var tableView: UITableView { get }
}

class SimpleTableView: UITableViewController, FooDelegate {

}

let delegate: FooDelegate? = SimpleTableView()

delegate?.tableView.reloadData()

记得在协议声明中添加@objc

答案 1 :(得分:1)

试试这个:

{
  test1: {
    name: "1",
    fa: true,
  },
  test2: {
    name: "2",
    fa: false,
  },
  test3: {
    name: "3",
    fa: true,
  }
}

如果您希望protocol FooDelegate: class where Self: UITableViewController { // code } 可以访问某些扩展程序:

UITableViewController
相关问题