1
votes

I have a working 10 minute countdown timer that updates the label each minute until it gets to less than one minute and it updates the label every second. I'm sure there is a more elegant way of doing 10 down to 2 minutes but I can't think of how to do the math and interpolate the time. Any ideas?

let countdown = 600

func countdownAction() {
  countdown -= 1

  if countdown > 540 {
    label.text = "10 minutes"
  } else if countdown > 480 {
    label.text = "9 minutes"
  } else if countdown > 420 {
    label.text = "8 minutes"
  } else if countdown > 360 {
    label.text = "7 minutes"
  } else if countdown > 300 {
    label.text = "6 minutes"
  } else if countdown > 240 {
    label.text = "5 minutes"
  } else if countdown > 180 {
    label.text = "4 minutes"
  } else if countdown > 120 {
    label.text = "3 minutes"
  } else if countdown > 60 {
    label.text = "2 minutes"
  } else if countdown > 0 {
    label.text = "1 minute"
  } else {
    label.text = "\(countdown) seconds"
  }
}
2
Think about how you can use % 60 and / 60 creatively. - Roope
Google about DateComponentsFormatter positionalTime - Leo Dabus
Not related to your question but you should never rely on a timer to measure elapsed time. Get the start date and use the Date property timeIntervalSinceNow to measure it. - Leo Dabus

2 Answers

1
votes
  • First check if countdown is less than 60 then print the seconds.
  • Otherwise use the modulo (%) operator to check for the values with 0 seconds. Then print the minutes (countdown / 60)

    var countdown = 600 // must be var !
    
    func countdownAction() {
        countdown -= 1
        if countdown < 60 {
            label.text = "\(countdown) seconds"
        } else if countdown % 60 == 0 {
            label.text = "\(countdown / 60) minutes"
        }
    }
    
1
votes

Using integer division you can simplify your code by using the result of dividing countdown by 60 and then have a special check for one minute and for seconds

func countDownAction() {
    countdown -= 1
    let value = countdown / 60

    if value > 1 {
        label.text = "\(value) minutes"
    } else if countdown >= 60 {
        label.text = "1 minute"
    } else {
        label.text = "\(countdown) seconds"
    }
}