How to calculate time if we have the distance and speed (kilometers per hour) in Swift

1 Answer

0 votes
import Foundation

// Initialize distance and speed
let distance: Double = 30.0 // (in km)
let speed: Double = 90.0    // (in km/h)

// Check to avoid division by zero
if speed <= 0 {
    fputs("Speed must be greater than zero.\n", stderr)
    exit(1) // exit with error code
}

// Calculate time
let tm: Double = distance / speed
print(String(format: "Time required: %.2f hours", tm))

// Optional: convert to hours and minutes
let hours: Int = Int(floor(tm))
let minutes: Int = Int(round((tm - Double(hours)) * 60))

print("Which is approximately \(hours) hours and \(minutes) minutes.")



/* run:

Time required: 0.33 hours
Which is approximately 0 hours and 20 minutes.

*/

 



answered Dec 6, 2025 by avibootz

Related questions

...