0

How do I to convert 1000kg to 1 short ton with current locale in Swift iOS? 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.

However if the default locale was in metric system it should be converted to metric tons. == 0.5 metric tons

I believe there should be a much more simplistic way than to do if statements like the following.

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
   }
}
JAL
  • 41,701
  • 23
  • 172
  • 300
user805981
  • 9,979
  • 8
  • 44
  • 64

1 Answers1

1

Use Locale to see if the device is set to use the metric system. 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
    }
}
JAL
  • 41,701
  • 23
  • 172
  • 300
  • why use converted instead of convert? – user805981 Dec 29 '16 at 00:34
  • @user805981 hmm, `convert` appeared as deprecated to me. But I guess you could make `kg` a `var` and use `convert`. Must have been a source editor hiccup. Use whichever you prefer. – JAL Dec 29 '16 at 00:35
  • would you recommend a switch statement instead of the large if else? – user805981 Dec 29 '16 at 00:37
  • @user805981 I just matched your pseudocode. I'm not sure how much a switch would help here. You could switch on local, but you'd still have additional checks on the converted value. – JAL Dec 29 '16 at 00:38
  • @JAL Isn't there some built in method that converts to the locale-correct unit, automatically? – Alexander Dec 29 '16 at 01:23
  • @Alexander not that I'm aware of, but I'm not too experienced with the Measurement API. – JAL Dec 29 '16 at 01:27