定制测量单位 [英] Custom measurement unit

查看:95
本文介绍了定制测量单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iOS 10中,Apple引入了一些量化测量的组件.例如:

In iOS 10, Apple introduced several components for quantifying measurements. For example:

let velocity = Measurement(value: 3, unit: UnitSpeed.metersPerSecond)

尽管很冗长,但好处是您可以转换为任何其他单元,而无需进行容易出错的内联计算:

Although verbose, the benefits are that you can convert to any other unit without error prone in-line calculations:

// before
let velocityMetersPerSecond = 3.0
let velocityKilometersPerHour = velocityMetersPerSecond * 1000 / 60

// after
let velocityKilometersPerHour = velocity.converted(to: .kilometersPerHour)

尽管Apple直接支持许多设备,但我需要一个他们不支持的设备.但是,Apple确实考虑了可扩展性,而引入新指标的方法之一是扩展Unit类:

While Apple supports many units straight out of the box, I have a need for a unit that they don't support. Apple did have extensibility in mind however, and one of the ways to introduce a new metric is by extending the Unit class:

extension UnitSpeed {
  static let furlongPerFornight = 
    UnitSpeed(symbol: "fur/ftn", converter: UnitConverterLinear(coefficient: 
      201.168 / 1209600.0)
}

我需要从meters/second中的源到min/km单位的速度.以下是转换的工作原理:

I need the speed from the source in meters/second to units of min/km. The following math below is how the conversion works:

min / km = 1 / (m / s) * 1000 / 60

我遇到的麻烦是如何将源值的乘法逆(或倒数)表达为转换.这是一个错误的版本:

The trouble I'm having is how to express the multiplicative inverse (or reciprocal) of the source value into the conversion. Here's a erroneous version:

extension UnitSpeed {
  // still missing 1 / source value!
  static let minutesPerKilometer = UnitSpeed(symbol: "min/km",
    UnitConverterLinear(coefficient: 1000.0 / 60.0)
}

推荐答案

由于转换不是线性的,因此您将需要创建自己的UnitConverter子类:

Since the conversion is not linear, you will need to create your own UnitConverter subclass:

class UnitConverterInverse: UnitConverter {
    var coefficient: Double

    init(coefficient: Double) {
        self.coefficient = coefficient
    }

    override func baseUnitValue(fromValue value: Double) -> Double {
        return coefficient / value
    }

    override func value(fromBaseUnitValue baseUnitValue: Double) -> Double {
        return coefficient / baseUnitValue
    }
}

extension UnitSpeed {
    static let minutesPerKilometer = UnitSpeed(symbol: "min/km",
        converter: UnitConverterInverse(coefficient: 1000.0 / 60.0))
}

let velocity = Measurement(value: 60, unit: UnitSpeed.milesPerHour)

let velocity2 = velocity.converted(to: .minutesPerKilometer)

print(velocity2)

0.621371192237334 min/km

这篇关于定制测量单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆