简体   繁体   English

如何根据语言环境在Swift iOS中使用当前语言环境将1000磅转换为1短吨?

[英]How to convert 1000 lbs to 1 short ton with current locale in Swift iOS depending on locale?

How do I to convert 1000kg to 1 short ton with current locale in Swift iOS? 如何在Swift iOS中以当前语言环境将1000kg转换为1短吨? The input is in kg. 输入单位为千克。 I want to output the string in either pounds or short tons depending on if it was over or below 1000 short tons. 我想以磅还是短吨来输出字符串,具体取决于它是大于还是小于1000短吨。

However if the default locale was in metric system it should be converted to metric tons. 但是,如果默认语言环境为公制,则应将其转换为公吨。 == 0.5 metric tons == 0.5公吨

I believe there should be a much more simplistic way than to do if statements like the following. 我相信应该有比下面的if语句简单得多的方法。

Example: 例:

let x = Measurement(value=1000, unit:UnitMass.kilograms)

if locale is metric and value is 1000kg and above{
// convert it metric tons
}else if not metric system{
   if x converted lbs and is above 1000lbs and above{
      //convert to short tons
   }else{ 
     //remain in lbs
   }
}

Use Locale to see if the device is set to use the metric system. 使用Locale查看设备是否设置为使用公制。 The rest is relatively straightforward: 其余的相对简单:

let kg = Measurement<UnitMass>(value: 1000, unit: .kilograms)

if Locale.current.usesMetricSystem && kg.value > 1000 {
    let tons = kg.converted(to: .metricTons)
} else {
    let lbs = kg.converted(to: .pounds)

    if lbs.value > 1000 {
        let shortTons = lbs.converted(to: .shortTons)
    } else {
        // lbs
    }
}

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

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