2017-06-13 114 views
2

我以前使用RxSwift,我决定我不想再使用它,并能够将所有内容转换为我更熟悉的Bond。由于新的变化,虽然债券V5,我似乎无法弄清楚如何观察UserDefaults中的值。以下代码最终给我一个致命的错误。ReactiveKit债券KVO观察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 
+0

如果你设置ofType为'Optional .self,'? –

+0

是的,这是完美的工作。如果我把正确的类型放进去,那肯定会有所帮助。随时回答,我会接受:) – SamG

+0

很高兴它的工作! :) –

回答

2

它可能不是很明显,但如果观察到的值可以是零,则ofType参数必须是一个可选类型。在你的情况下,这将是:

userDefaults.reactive 
    .keyPath(LocationManager.HomeLocationKey, ofType: Optional<String>.self, context: .immediateOnMain) 
    ...