我正在尝试检查 UserDefaults 键是否存在,如果不存在,则将其设置为我选择的标准值,但此处关于堆栈溢出的答案并没有帮助我完成这项工作。
基本上我有几个 UISwitch,一个打开,其余的从一开始就设置为关闭。现在我的问题是,当加载 viewController 并且这些键不存在时,我不知道如何将这些初始状态保存到 UserDefaults 中。
这就是我尝试检查 UISwitch 的 key 是否存在以及是否将其设置为 true 的方式(因为这是我想要的状态),然后再次检查 key 的 bool 是什么并设置 UISwitch对它(这在 viewController 再次打开时非常重要):
func setupSwitches() {
let defaults = UserDefaults.standard
//check if the key exists
if !defaults.bool(forKey: "parallax") {
switchParallax.setOn(true, animated: true)
}
//check for the key and set the UISwitch
if defaults.bool(forKey: "parallax") {
switchParallax.setOn(true, animated: true)
} else {
switchParallax.setOn(false, animated: true)
}
}
当用户按下相应的按钮时,我会像这样设置 UserDefaults 键:
@IBAction func switchParallax_tapped(_ sender: UISwitch) {
let defaults = UserDefaults.standard
if sender.isOn == true {
defaults.set(true, forKey: "parallax")
} else {
defaults.set(false, forKey: "parallax")
}
}
这显然是可行的,但问题出在上面的第一段代码中。
首先,我不确定如何检查它是否存在,如果不存在则将其设置为“true”,并且由于该函数称为 setupSwitches(),所以它会在每次显示 viewController 时运行。
所以我不知道是否有更好的方法(例如,由于内存问题)来检查 key 是否存在,如果不存在则将其设置为 true,如果它已经存在则从 UserDefaults 获取 bool 并设置切换到正确的状态。
最佳答案
问题是您无法确定 UserDefaults.standard.bool(forKey: key)
是否存在。 UserDefaults.standard.object(forKey: key)
返回 Any?
因此您可以使用它来测试 nil,例如
extension UserDefaults {
static func exists(key: String) -> Bool {
return UserDefaults.standard.object(forKey: key) != nil
}
}
关于ios - swift : How to check if UserDefaults exists and if not save a chosen standard value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47581644/