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.
Apple Weather App
The unitStyle is short.

