什么是swift中objc的`UIViewController <MyProtocol>`的等价物?

nac*_*o4d 3 objective-c swift

我想声明一个接受采用特定协议的UIViewController的函数.我如何在swift中声明这个?

protocol MyProtocol {
    func subtitle() -> String
    func saveResults()
}

func setupViewController(controller: UIViewController<MyProtocol> ) { // ERROR here
    ...
}
Run Code Online (Sandbox Code Playgroud)

为什么我要这样做:
因为我创建了一个容器视图控制器,它有几个不同类的子项.他们的共同点是MyProtocol,他们继承(直接或间接)的事实UIViewController.

所以我的一个方法有一个这个控制器作为参数.我想告诉编译器可能的最具体的信息:对象是一个UIViewController并且符合MyProtocol.我该如何申报?

Zel*_* B. 6

我不太了解objective-c,但它看起来甚至比你使用泛型来实现你所要求的(不能说肯定因为我不知道obj-​​c中的泛型语法).在swift中使用泛型,你的setupViewController函数应该是这样的:

func setupController<T:UIViewController where T:MyProtocol>(controller : T){

}
Run Code Online (Sandbox Code Playgroud)

这在功能方面完全等同于objective-c的方法