Pressing_Keys_24_7
Pressing_Keys_24_7

Reputation: 1863

How to Display Best Time in an iOS Game with 3 Significant Digits Decimal Value?

I am saving the best time in my iOS Game using the following functions:-

func format(timeInterval: TimeInterval) -> String {
let interval = Int(timeInterval)
let seconds = interval % 60
let minutes = (interval / 60) % 60
let milliseconds = Int(timeInterval * 1000) % 1000
return String(format: "%02d:%02d.%03d", minutes, seconds, milliseconds)
}

func setBestTime(with time: Int){
    let defaults = UserDefaults.standard
    let previousBestTime = defaults.integer(forKey: "bestTime")
    defaults.set(time > previousBestTime ? time : previousBestTime, forKey: "bestTime")
}

func getBestTime(){
    self.bestTimeLabel.text = "\(UserDefaults.standard.integer(forKey: "bestTime"))"
}

func gameOver() {
stopGame()
setBestTime(with: Int(elapsedTime))
}

But, it displays the best time in integer. I want the best time to be displayed in decimal with 3 significant figures. Could anyone please let me know how can I do that? Thanks for the help!

Upvotes: 0

Views: 31

Answers (1)

David Pasztor
David Pasztor

Reputation: 54775

You aren't calling your format function. You simply need to pass the Int value retrieve from UserDefault to format before displaying it on your label.

You should also use UserDefaults.double if you want to store a TimeInterval rather than an Int.

let defaults = UserDefaults.standard
let bestTimeKey = "bestTime"

func format(timeInterval: TimeInterval) -> String {
    let interval = Int(timeInterval)
    let seconds = interval % 60
    let minutes = (interval / 60) % 60
    let milliseconds = Int(timeInterval * 1000) % 1000
    return String(format: "%02d:%02d.%03d", minutes, seconds, milliseconds)
}

func setBestTime(with time: TimeInterval){
    let previousBestTime = defaults.double(forKey: bestTimeKey)
    defaults.set(max(time, previousBestTime), forKey: bestTimeKey)
}

func getBestTime() {
    let bestTime = defaults.double(forKey: bestTimeKey)
    let formattedBestTime = format(timeInterval: bestTime)
    bestTimeLabel.text = formattedBestTime
}

func gameOver() {
    stopGame()
    setBestTime(with: elapsedTime)
}

Upvotes: 2

Related Questions