Search code examples
swiftcllocationmanagercllocation

Swift fetch minutes per kilometer from seconds per meter


I have an array of CLLocations each with the seconds per meter element. I want to calculate the run splits from that array (Minutes per kilometer). How can I fetch the minutes per kilometer for each kilometer from the CLLocations array?

This is how I am getting the locations below.

let query = HKWorkoutRouteQuery(route: route) { (_, locations, _, error) in
        if let error = error {
            print("There was an error fetching route data: ", error)
            return
        }

        guard let locations = locations else { return }
    }
    healthStore.execute(query)

Solution

  • CLLocationSpeed is defined as speed in meters per second, see Apple Docs

    It is an alias for Double, so you can just translate it with:

    let speedMS = location.speed
    let speedKMM = speedMS * 3 / 50
    

    You can use an extension for better code readability:

    extension CLLocationSpeed {
        func toKmM() -> Double {
            return self * 3 / 50
        }
    }
    

    And when you want to get km/m, you just use CLLocation.speed.toKmM()

    Edit:
    And even simpler solution by @Leo Dabus, extend CLLocation:

    extension CLLocation { 
        var kilometersPerMinute: Double { 
            speed * 0.06 
        } 
    }