In this post, I’ll share how to display the temperature with unit using the MeasurementFormatter.

MeasurementFormatter

let numFormatter = NumberFormatter()
numFormatter.maximumFractionDigits = 0

let measureFormatter = MeasurementFormatter()
measureFormatter.numberFormatter = numFormatter

let kelvin: Double = 294
var temperature: String = ""

let kelvinTemperature = Measurement(
    value: kelvin,
    unit: UnitTemperature.kelvin
)

//temperature is automatically changed the celcius / farenheit depending on locale.
temperature = measureFormatter.string(from: kelvinTemperature)

//70°F
print(temperature)

 

UnitStyle

//70 degrees Fahrenheit
measureFormatter.unitStyle = .long
//70°F
measureFormatter.unitStyle = .medium
//70°
measureFormatter.unitStyle = .short

The default unitStyle is medium. You can set the three different unitStyle.

weather.PNG

Apple Weather App

The unitStyle is short.

Quote of the week

"People ask me what I do in the winter when there's no baseball. I'll tell you what I do. I stare out the window and wait for spring."

~ Rogers Hornsby