Reputation: 1863
I have used user defaults to save the player's best time. Right now, I am only able to save the Player's last played timing through the use of the following code. I want the time to be the best time only if it is more (greater than) the previous time. Could anyone please let me know how can I do that? Will appreciate your help! Thanks!
func setBestTime(with time:String){
let defaults = UserDefaults.standard
defaults.set(time, forKey: "bestTime")
}
func getBestTime(){
let defaults = UserDefaults.standard
if let time = defaults.value(forKey: "bestTime") as? String {
self.bestTimeLabel.text = "Best Time: \(time)"
}
}
Upvotes: 0
Views: 63
Reputation: 3446
I would rather store the time as a number (like Int or Double). This allows you to compare times (easily), which is useful for your goal.
Besides, I would advice you to keep the get and set functions simple, instead of having them also do some UI-related things.
So, your get and set functions could be like this:
func setBestTime(with time: Double) {
let defaults = UserDefaults.standard
defaults.set(time, forKey: "bestTime")
}
func getBestTime() -> Double? {
let defaults = UserDefaults.standard
if let time = defaults.value(forKey: "bestTime") as? Double {
return time
}
return 0.0 // If there is no time stored, return some default value.
}
As you see, they do nothing more or less than you would expect from their names.
So, now you want to save the new time only if it's greater than the saved time. How to do that, depends on where in the rest of you code you call these functions. You could do something like this:
// Setup
let oldBest = getBestTime()
self.bestTimeLabel.text = "Best Time: \(oldBest)"
// After the player has played a game
// I assume you get the new time from somewhere
let newTime = ...
// Set new best if applicable
if newTime > oldBest {
// So, the player has a new best, let's save that
setBestTime(with: newTime)
// Make the UI display that new best time
self.bestTimeLabel.text = "Best Time: \(newTime)"
}
Hope this will inspire you!
Upvotes: 1
Reputation: 1138
First of all you should store the best time as a Double as it will be a lot easier for you to to do what you want here. And then all you have to do is compare the stored value with the new one to determine which one to store:
func setBestTime(with time: Double){
let defaults = UserDefaults.standard
let previousBestTime = defaults.double(forKey: "bestTime")
defaults.set(time > previousBestTime ? time : previousBestTime, forKey: "bestTime")
}
func getBestTime(){
self.bestTimeLabel.text = "Best Time: \(UserDefaults.standard.double(forKey: "bestTime"))"
}
Upvotes: 1