比方说,我有一个协议,斯威夫特类和协议继承斯威夫特
protocol SearchCompletionProtocol {
func searchSuccessful(results: [AnyObject])
func searchCancelled()
}
现在,让我们说,我有一个类,并在init方法我想在一个单一的参数来传递。限制是我希望这个参数的类型为UIViewController
,并且也符合SearchCompletionProtocol
协议。我会怎么做呢?以下是我尝试过的一些事例,它们都不起作用。
class SearchDelegate: UISearchDisplayController, UISearchBarDelegate {
let completionDelegate: SearchCompletionProtocol
init<T: SearchCompletionProtocol where T: UIViewController>(completionDelegate: T) {
self.completionDelegate = completionDelegate
let _searchBar = UISearchBar()
super.init(searchBar: _searchBar, contentsController: completionDelegate)
}
}
我也试着将协议的继承限制为只有类型为UIViewController的类,但那也行不通。
protocol SearchCompletionProtocol: class, UIViewController {
func searchSuccessful(results: [AnyObject])
func searchCancelled()
}
当然,我可以很容易地就在两个参数传递给该方法,一个符合搜索协议和类型的UIViewController之一是,但只是似乎不怎么SWIFTY。
http://stackoverflow.com/questions/25214484/how-do-i-的重复declare-a-variable-that-has-a-type-and-implement -a-protocol? –
你的构造函数看起来像在哪里调用它? –
@MartinR是非常接近。但是我会认为这是一个错误的答案,因为它更像是一种黑客行为。是的,它编译,是的它会让你最终的结果,但它的丑陋。在我这样做之前,我只做两个参数。 –