2015-01-16 115 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() 
}