Swift 从每米秒数获取每公里分钟数

Swift fetch minutes per kilometer from seconds per meter

我有一个 CLLocations 数组,每个数组都有每米秒数元素。我想计算该数组的 运行 拆分(每公里分钟数)。如何从 CLLocations 数组中获取每公里的分钟数?

这就是我获取以下位置的方式。

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 定义为以米每秒为单位的速度,参见 Apple Docs

它是 Double 的别名,因此您可以将其翻译为:

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

您可以使用扩展来提高代码可读性:

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

而当你想获得km/m时,你只需使用CLLocation.speed.toKmM()

编辑:
@Leo Dabus 提供的更简单的解决方案,扩展 CLLocation:

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

您还可以创建自己的速度单位扩展 UnitSpeed。这样做的好处是您可以关联一个符号并获得对转换的更多控制:

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