Nick89 Nick89 - 1 year ago 115
Swift Question

Convert Kelvin into Celsius in Swift

I'm trying to retrieve the temperature from the users current location.

I am using the API from OpenWeatherMap. The problem is, they provide the temperature in Kelvin as default, and I would like it in Celsius.

I understand that I just need to subtract 273.15 from the kelvin value....? But i'm struggling to figure out where to do that.

My code for setting my labels:

var jsonData: AnyObject?

func setLabels(weatherData: NSData) {

do {

self.jsonData = try NSJSONSerialization.JSONObjectWithData(weatherData, options: []) as! NSDictionary

} catch {
//handle error here


if let name = jsonData!["name"] as? String {

locationLabel.text = "using your current location, \(name)"


if let main = jsonData!["main"] as? NSDictionary {
if let temperature = main["temp"] as? Double {

self.tempLabel.text = String(format: "%.0f", temperature)




Can anyone help me get this right please, as I'm really not sure where to start, thanks.

Let me know if you need to see more of my code.

Answer Source
if let kelvinTemp = main["temp"] as? Double {
    let celsiusTemp = kelvinTemp - 273.15
    self.tempLabel.text = String(format: "%.0f", celsiusTemp)

or simply

self.tempLabel.text = String(format: "%.0f", temperature - 273.15)