2015-01-16 117 views
0

比方说,我有一个协议,斯威夫特类和协议继承斯威夫特

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。

+0

http://stackoverflow.com/questions/25214484/how-do-i-的重复declare-a-variable-that-has-a-type-and-implement -a-protocol? –

+0

你的构造函数看起来像在哪里调用它? –

+0

@MartinR是非常接近。但是我会认为这是一个错误的答案,因为它更像是一种黑客行为。是的,它编译,是的它会让你最终的结果,但它的丑陋。在我这样做之前,我只做两个参数。 –

回答

0

所以看起来像这样的解决方案是我剥离了我原来的代码,认为它并不重要。这里是我的原始代码

protocol SearchCompletionProtocol { 
    func searchSuccessful(results: [RTruck]) 
    func searchCancelled() 
} 

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) 
     self.completionDelegate.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "showSearchBar") 
    } 
} 

这里的问题是,我用self.completionDelegate.navigationItem。类级别的completionDelegate的类型就是SearchCompletionProtocol,它不是T类型的。除去self导致它使用传入的参数,这个参数在编译器的眼中是一个UIViewController,一切正常。这里的工作代码

protocol SearchCompletionProtocol { 
    func searchSuccessful(results: [RTruck]) 
    func searchCancelled() 
} 

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) 
     completionDelegate.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "showSearchBar") 
    } 
} 
0

在斯威夫特4您可以用新的&标志实现这一目标:

func foo(vc: UIViewController & SearchCompletionProtocol) { 
    vc.searchCancelled() 
}