比方說,我有一個協議,斯威夫特類和協議繼承斯威夫特
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是非常接近。但是我會認爲這是一個錯誤的答案,因爲它更像是一種黑客行爲。是的,它編譯,是的它會讓你最終的結果,但它的醜陋。在我這樣做之前,我只做兩個參數。 –