gpt4 book ai didi

swift - ReactiveKit Bond KVO 观察 UserDefaults

转载 作者:可可西里 更新时间:2023-11-01 00:57:05 24 4
gpt4 key购买 nike

我之前使用过 RxSwift,但我决定不再使用它,并且能够将所有内容转换为我更熟悉的 Bond。由于 Bond v5 的新变化,我似乎无法弄清楚如何观察 UserDefaults 中的值。以下代码最终会给我一个 fatal error 。

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

最佳答案

可能不是很明显,但是如果观察到的值可以是 nil,则 ofType 参数必须是 Optional 类型。在您的情况下,这将是:

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

关于swift - ReactiveKit Bond KVO 观察 UserDefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44531293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com