【发布时间】:2017-11-15 19:26:42
【问题描述】:
我以前使用 RxSwift,但我决定不再使用它,并且能够将所有内容转换为我更熟悉的 Bond。由于 Bond v5 的新变化,我似乎无法弄清楚如何观察 UserDefaults 中的值。以下代码最终给了我一个致命错误。
userDefaults.reactive
.keyPath(LocationManager.HomeLocationKey, ofType: String.self, context: .immediateOnMain)
.map(self.initLocation(from:))
.bind(to: self.homeLocation)
userDefaults 是对 UserDefaults.standard 的引用,LocationManager.HomeLocationKey 是一个字符串。我在下面提供initLocation 函数,因为我知道它会被要求。在该功能下方,我将发布应用启动后收到的错误。
func initLocation(from string: String?) -> Location?
{
guard let dataString = string
else { log.warning("Location data did not exist, returning nil"); return nil }
let json = JSON.parse(dataString)
return Location(from: json)
}
错误:
fatal error: Could not convert nil to String. Maybe `dynamic(keyPath:ofExpectedType:)` method might be of help?): file /Users/sam/Documents/iOS Apps/Drizzle/Pods/Bond/Sources/Shared/NSObject+KVO.swift, line 58
【问题讨论】:
-
设置ofType为
Optional<String>.self,是否有效? -
是的,效果很好。如果我输入正确的类型肯定会有所帮助,呵呵。随意回答,我会接受:)
-
很高兴它成功了! :)
标签: swift userdefaults reactivekit swiftbond