RxSwift:观察存储在 UserDefaults 中的数组

RxSwift: observe an array stored in UserDefaults

我正在尝试观察我的 UserDefaults 以监控对 locations 的更改,它是 CLLocationCoordinate2D.

的数组

这是我正在尝试的:

extension UserDefaults {

    var ob: Observable<[CLLocationCoordinate2D]> {
        return self.rx.observe(Array.self, "locations")
    }

}

但是我得到这个错误:

no 'observe' candidates produce the expected contextual result type 'Observable<[CLLocationCoordinate2D]>' (aka 'Observable<Array<CLLocationCoordinate2D>>

有什么想法吗?谢谢!

observe 将 return 一个可选元素的 ObservableObservable<[CLLocationCoordinate2D]?>

这不是一个很好的错误。如果它说 看到你尝试 return 的类型,而不是它预期的类型,那会更有帮助。

您可能已经看到这一点的一种方法是创建一个变量,然后 return 改为使用它。

var ob: Observable<[CLLocationCoordinate2D]> {
    let a = self.rx.observe(Array<CLLocationCoordinate2D>.self, "locations")
    return a
}

您将能够看到 a 是什么类型 (Observable<[CLLocationCoordinate2D]?>),并且还会收到更好的错误消息:

Cannot convert return expression of type 'Observable<[CLLocationCoordinate2D]?>' (aka 'Observable<Optional<Array<CLLocationCoordinate2D>>>') to return type 'Observable<[CLLocationCoordinate2D]>' (aka 'Observable<Array<CLLocationCoordinate2D>>')

因此,更正该错误,您的代码应如下所示:

var ob: Observable<[CLLocationCoordinate2D]?> {
    return self.rx.observe(Array.self, "locations")
}

尽管我建议您不要依赖类型推断,而是明确说明数组的元素类型。 Swift 已经够艰难了:

var ob: Observable<[CLLocationCoordinate2D]?> {
    return self.rx.observe(Array<CLLocationCoordinate2D>.self, "locations")
}