繁体   English   中英

Swift中的类和协议继承

[英]Class and Protocol Inheritance in Swift

假设我在Swift中有一个协议

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。

因此,解决方案似乎是我剥离了原始代码,认为它并不重要。 这是我的原始代码

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")
    }
}

在Swift 4中,您可以使用新的&符号实现此目的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM