简体   繁体   English

从每米秒快速获取每公里分钟数

[英]Swift fetch minutes per kilometer from seconds per meter

I have an array of CLLocations each with the seconds per meter element.我有一个CLLocations数组,每个数组都有每米元素的秒数。 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?如何从CLLocations数组中获取每公里每公里的分钟数?

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)

CLLocationSpeed is defined as speed in meters per second, see Apple Docs CLLocationSpeed定义为以米/秒为单位的速度,请参阅Apple Docs

It is an alias for Double , so you can just translate it with:它是Double的别名,因此您可以将其翻译为:

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()当你想得到公里/米时,你只需使用CLLocation.speed.toKmM()

Edit:编辑:
And even simpler solution by @Leo Dabus, extend CLLocation: @Leo Dabus 提供的更简单的解决方案,扩展 CLLocation:

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

You can also create your own speed unit extending UnitSpeed.您还可以创建自己的速度单位扩展 UnitSpeed。 The advantage of doing it this way is that you can associate a symbol and gain much more control over the conversions:这样做的好处是您可以关联符号并获得对转换的更多控制:

extension UnitSpeed {
    static var metersPerMinute: UnitSpeed = .init(symbol: "m/min", converter:  UnitConverterLinear(coefficient: 1 / 60))
    static var kilometersPerMinute: UnitSpeed = .init(symbol: "km/min", converter:  UnitConverterLinear(coefficient: 50 / 3))
}

let metersPerSecond = Measurement<UnitSpeed>(value: 30, unit: .metersPerSecond)
let kilometersPerHour = metersPerSecond.converted(to: .kilometersPerHour)      // 107.9999136000691 km/h
let kilometersPerMinute = metersPerSecond.converted(to: .kilometersPerMinute)  // 1.7999999999999998 km/min
let formatter = MeasurementFormatter()
formatter.unitStyle = .medium
formatter.unitOptions = .providedUnit
formatter.numberFormatter.maximumFractionDigits = 1
formatter.string(from: kilometersPerHour)      // "108 km/h"
formatter.string(from: kilometersPerMinute)    // "1.8 km/min"

UnitSpeed.kilometersPerMinute.converter.value(fromBaseUnitValue: 1) // 0.06

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM