在 swift 中对系统协议可选要求进行通用实现的最简单方法是什么?

What is the easiest way to make a common implementation for system protocol optional requirement in swift?

这是系统协议和可选要求。

public protocol WKNavigationDelegate : NSObjectProtocol {

    @available(iOS 8.0, *)
    optional func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
}

假设有多个 ViewController 需要实现这个协议。

class ViewController1: UIViewController, WKNavigationDelegate { } // default
class ViewController2: UIViewController, WKNavigationDelegate { } // default

class ViewController3: UIViewController, WKNavigationDelegate { 

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        print("Override Success!")
    }
}

如果它没有像我们为自定义协议那样在 ViewController 中实现,我是否可以为该协议提供默认实现。

extension WKNavigationDelegate {

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        print("Success!") // default implementation doesn't seem to work for system protocol
    }
}

您可以扩展基础 class UIViewController 并使用默认实现

使其符合系统协议 WKNavigationDelegate
extension UIViewController : WKNavigationDelegate  {

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        print("Success!")
    }
}

并在 subclasses

中覆盖它