I'm trying to compare a value that was saved to UserDefaults to a new integer but I cant figure it out.
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 {
}
}
How can I change the value from defaults.object(forKey: "HighScore") to be an integer so I can compare them?
First of all, you can use
UserDefaults.standar.integer(forKey:)to retrieve a value of typeInt. Secondly, you should store the casted value once and shouldn't retrieve it several times (currently you retrieve it 3 times instead of just 1).Moreover, your logic is flawed. You are trying to compare the value if the retrieved value was
nil. So you are not just trying to compareAny?toInt, you are trying to compareniltoInt.The same function, but retrieving the
Intvalue straight away without having to cast (UserDefaults.integer(forKey:)returns 0 if there is no value stored for that key).