首页 > 解决方案 > 在枚举之前使用 '\' 观察实现

问题描述

最近我实现了一个进度视图来显示网页上的加载过程。我阅读了一个示例(https://gist.github.com/fxm90/50d6c73d07c4d9755981b9bb4c5ab931)并进行了修改。但是部分代码对我来说并不清楚,确切地说

\.estimatedProgress

这是相关的代码。

var webView: WKWebView!
// Progress view reflecting the current loading progress of the web view.
let progressView = UIProgressView(progressViewStyle: .default)
/// The observation object for the progress of the web view (we only receive notifications until it is deallocated).
private var estimatedProgressObserver: NSKeyValueObservation?

private func setupEstimatedProgressObserver() {
    estimatedProgressObserver = webView.observe(\.estimatedProgress, options: [.new]) { [weak self] webView, _ in
        self?.progressView.progress = Float(webView.estimatedProgress)
    }
}

问题

  1. 为什么以及何时可以在枚举之前使用字符“\”?
  2. 是否不需要使用这种方式进行 deinit 或删除观察者?为什么?

标签: iosswiftobservers

解决方案


\<Type>.<path>语法是Swift Key-Path 表达式(而不是枚举),本质上是对 some 路径的强类型引用Type。当可以推断出类型时,您可以省略它,因此表达式变为\.path(在您的示例中,完整表达式为\WKWebView.estimatedProgress)。

上面的链接中有几个示例可以帮助您更好地理解这一点。

对于第二部分,观察只会持续只要estimatedProgressObserver没有被释放(所以,只要有东西对它有很强的引用)。


推荐阅读