如何更改UserDefaults中某个值的类型?
问题描述:
我试图比较一个保存到UserDefaults的值为一个新的整数,但我无法弄清楚。如何更改UserDefaults中某个值的类型?
func setScore() {
let defaults = UserDefaults.standard
let newScore = score
if defaults.object(forKey: "HighScore") != nil {
defaults.set(newScore, forKey: "HighScore")
let highScore = defaults.object(forKey: "HighScore") as! Int
print(highScore)
} else if defaults.object(forKey: "HighScore") < Int(newScore) {
defaults.set(newScore, forKey: "HighScore")
let highScore = defaults.object(forKey: "HighScore") as! Int
print(highScore)
} else {
}
}
我怎样才能改变从defaults.object(forKey: "HighScore")
值是一个整数,这样我就可以对它们进行比较?
答
首先,您可以使用UserDefaults.standar.integer(forKey:)
来检索Int
类型的值。其次,你应该存储铸造值一次,不应该多次检索(目前你检索3次而不是1次)。
此外,你的逻辑是有缺陷的。如果检索值为nil
,则试图比较该值。所以你不只是想比较Any?
到Int
,你试图比较nil
到Int
。
func setScore() {
let defaults = UserDefaults.standard
let newScore = score
if let highScore = defaults.object(forKey: "HighScore") as? Int {
print(highScore)
if highScore < Int(newScore) {
defaults.set(newScore, forKey: "HighScore")
}
}
}
相同的功能,但检索Int
值马上而无需进行转换(UserDefaults.integer(forKey:)
返回0,如果没有存储该密钥值)。
func setScore() {
let newScore = score
if UserDefaults.standard.integer(forKey: "HighScore") < Int(newScore) {
defaults.set(newScore, forKey: "HighScore")
}
}
}
+0
谢谢,由于某种原因,我认为我需要零声明,但我没有。现在完美运作。 –
你看过'UserDefaults'的文档吗?有阅读特定类型的方法。 – rmaddy
https://stackoverflow.com/questions/29930736/making-nsuserdefault-of-type-integer-in-swift – toddg
请注意,只有在defaults.object(forKey: “HighScore”)是零,所以你的比较没有多大意义。 – Caleb