Define
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
Use
> secondsToHoursMinutesSeconds(27005)
(7,30,5)
or
let (h,m,s) = secondsToHoursMinutesSeconds(27005)
The above function makes use of Swift tuples to return three values at once. You destructure the tuple using the let (var, ...)
syntax or can access individual tuple members, if need be.
If you actually need to print it out with the words Hours
etc then use something like this:
func printSecondsToHoursMinutesSeconds (seconds:Int) -> () {
let (h, m, s) = secondsToHoursMinutesSeconds (seconds)
print ("(h) Hours, (m) Minutes, (s) Seconds")
}
Note that the above implementation of secondsToHoursMinutesSeconds()
works for Int
arguments. If you want a Double
version you'll need to decide what the return values are - could be (Int, Int, Double)
or could be (Double, Double, Double)
. You could try something like:
func secondsToHoursMinutesSeconds (seconds : Double) -> (Double, Double, Double) {
let (hr, minf) = modf (seconds / 3600)
let (min, secf) = modf (60 * minf)
return (hr, min, 60 * secf)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…