-1

I have some text fields in an array. HH:MM:SS. I'm having two issues, one is when one of the fields is left blank, the app crashes and I want it to just read as "0" if blank. Second, I use below to convert HH:MM:SS to Minutes. I do 0:18:30 and the math below to decimal comes out to 18.5

Now how would I convert this back to HH:MM:SS? array[0] is hours, array[1] is minutes, array[2] is seconds.

stepOne = (Float(array[0])! * 60) + Float(array[1])! + (Float(array[2])! / 60)
Asperi
  • 228,894
  • 20
  • 464
  • 690
Dewan
  • 429
  • 3
  • 16
  • 4
    Why are you fildding around with all these multiplications, additions, force unwraps? Just use `DateFormatter`. – Alexander Feb 14 '20 at 18:56
  • I think this will help you. Take a look into [this](https://stackoverflow.com/questions/26794703/swift-integer-conversion-to-hours-minutes-seconds/43890305) – user2688814 Feb 14 '20 at 18:58

1 Answers1

1

What you need is to calculate the number of seconds instead of number of minutes. Using the reduce method just multiply the first element by 3600 and then divide the multiplier by 60 after each iteration. Next you can use DateComponentsFormatter to display the resulting seconds time interval using .positional units style to the user:

let array = [0,18,30]
var n = 3600
let seconds = array.reduce(0) {
    defer { n /= 60 }
    return $0 + $1 * n
}

let dcf = DateComponentsFormatter()
dcf.allowedUnits = [.hour, .minute, .second]
dcf.unitsStyle = .positional
dcf.zeroFormattingBehavior = .pad
let string = dcf.string(from: TimeInterval(seconds))  // "00:18:30"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571