How to change the type of a value from UserDefaults?

1.3k views Asked by At

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?

1

There are 1 answers

1
Dávid Pásztor On BEST ANSWER

First of all, you can use UserDefaults.standar.integer(forKey:) to retrieve a value of type Int. 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 compare Any? to Int, you are trying to compare nil to 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")
        }
    }
}

The same function, but retrieving the Int value straight away without having to cast (UserDefaults.integer(forKey:) returns 0 if there is no value stored for that key).

func setScore() {
    let newScore = score
    if UserDefaults.standard.integer(forKey: "HighScore") < Int(newScore) {
            defaults.set(newScore, forKey: "HighScore")
        }
    }
}