Convert Fahrenheit to Celsius and vice versa in Swift


To convert temperature between Fahrenheit and Celsius and vice versa, you don’t need to remember the formula you learned in high school. This is because the Foundation framework provides a feature to create Measurement instance to make the task easier for iOS developers.

Using a Measurement instance of the Foundation framework, you can efficiently perform conversion tasks between units without knowing any formula. It can be used for conversion of temperature from fahrenheit to celsius and vice versa.

Convert the temperature from Fahrenheit to Celsius

Below is an example where we are converting temperature from Fahrenheit to Celsius unit:

import Foundation

let celsius = Measurement(value: 30, unit: UnitTemperature.celsius)
let fahrenheit = celsius.converted(to: .fahrenheit).value

print(fahrenheit)

Output:

85.99999999999557

In the above program, we have created an instance of Measurement that contains the celsius value of temperature. The value parameter is the value of temperature in Celsius. We have used the property UnitTemperature.celsius to define the value as a celsius unit.

In the end we are using the converted() method to convert our celsius value to fahrenheit. We store the fahrenheit value to the fahrenheit variable.

Convert the temperature from Celsius to Fahrenheit

Now let’s do the same thing in vice versa, i.e convert the temperature from Celsius to Fahrenheit in Swift programming. Below is the program given for this task:

import Foundation

let fahrenheit = Measurement(value: 66.0, unit: UnitTemperature.fahrenheit)
let celcius = fahrenheit.converted(to: .celsius).value

print(celcius)

Output:

18.888888888891245

In the above program, we started a Measurement instance which is the Fahrenheit value of temperature. After that, we have used the converted() method toc convert the fahrenheit value to celsius.