iOS Build a Weather App Modeling Forecast Data Icon Images

Juan Jimenez
Juan Jimenez
4,389 Points

Why does Pasan use an extension?

In the build a weather app it starts with this code:

import Foundation import UIKit

struct CurrentWeather { let temperature: Double let humidity: Double let precipProbability: Double let summary: String let icon: String

}

extension CurrentWeather { var iconImage: UIImage { switch icon { case "clear-day": return #imageLiteral(resourceName: "clear-day") case "clear-night": return #imageLiteral(resourceName: "clear-night") case "rain": return #imageLiteral(resourceName: "rain") case "snow": return #imageLiteral(resourceName: "snow") case "sleet": return #imageLiteral(resourceName: "sleet") case "wind": return #imageLiteral(resourceName: "wind") case "fog": return #imageLiteral(resourceName: "fog") case "cloudy": return #imageLiteral(resourceName: "cloudy") case "partly-cloudy-day": return #imageLiteral(resourceName: "partly-cloudy-day") case "partly-cloudy-night": return #imageLiteral(resourceName: "partly-cloudy-night") default: return #imageLiteral(resourceName: "default") } } }

Why is using an extension preferred over writing the same code inside the struct?

1 Answer

Marcus Klausen
Marcus Klausen
14,508 Points

Hi,

The computed property, is used to help setting the right value for icon property.

But it isn't really in itself part of the CurrentWeather type.

You could think of it like a helper method, like when we break down big functions so that we have better reusability and the code is easier to read.

Cheers :-)