I am having some problems while attempting to compare my score and highscore to see which one is bigger and then save it. I think the problem lies in the comparison and savi
You can also create a new NSUserDefault property with a getter and a setter to automatically check if the score you are trying to save it is higher than the actual high score:
update: Xcode 8.2.1 • Swift 3.0.2
extension UserDefaults {
static let highScoreIntegerKey = "highScoreInteger"
static let highScoreDoubleKey = "highScoreDouble"
var highScore: Int {
get {
print("High Score:", integer(forKey: UserDefaults.highScoreIntegerKey))
return integer(forKey: UserDefaults.highScoreIntegerKey)
}
set {
guard newValue > highScore
else {
print("\(newValue) ≤ \(highScore) Try again")
return
}
set(newValue, forKey: UserDefaults.highScoreIntegerKey)
print("New High Score:", highScore)
}
}
func resetHighScore() {
removeObject(forKey: UserDefaults.highScoreIntegerKey)
print("removed object for highScoreIntegerKey")
}
var highScoreDouble: Double {
get {
return double(forKey: UserDefaults.highScoreDoubleKey)
}
set {
guard newValue > highScoreDouble
else {
print("\(newValue) ≤ \(highScoreDouble) Try again")
print("Try again")
return
}
set(newValue, forKey: UserDefaults.highScoreDoubleKey)
print("New High Score:", highScoreDouble)
}
}
func resetHighScoreDouble() {
removeObject(forKey: UserDefaults.highScoreDoubleKey)
print("removed object for highScoreDoubleKey")
}
}
testing in a Project (doesn't work in playground since Swift 2):
UserDefaults().resetHighScore()
UserDefaults().highScore // High Score = 0
UserDefaults().highScore = 100 // New High Score = 100
UserDefaults().highScore = 50 // 50 < 100 Try again
UserDefaults().highScore // 100
UserDefaults().highScore = 150 // New High Score = 150
UserDefaults().highScore // 150
Xcode 7.2 • Swift 2.1.1
extension NSUserDefaults {
var highScore: Int {
get {
print("High Score = " + integerForKey("highScore").description)
return integerForKey("highScore")
}
set {
guard newValue > highScore else { print("\(newValue) ≤ \(highScore) Try again")
return
}
setInteger(newValue, forKey: "highScore")
print("New High Score = \(highScore)")
}
}
func resetHighScore() {
removeObjectForKey("highScore")
print("removed object for key highScore")
}
var highScoreDouble: Double {
get {
return doubleForKey("highScoreDouble")
}
set {
guard newValue > highScoreDouble else { print("Try again")
return
}
setDouble(newValue, forKey: "highScoreDouble")
print("New High Score = \(highScoreDouble)")
}
}
func resetHighScoreDouble() {
removeObjectForKey("highScoreDouble")
print("removed object for key highScoreDouble")
}
}
Read your code carefully and you should be able to find the errors.
score
to highscore
.highscore
from NSUserDefaults
.synchronize
.Swift 2: You have set an integer value in userDefaults so, you may try retrieve it using, defaults.integerForKey(score, forKey: "highscore")