Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Weather App Modeling Forecast Data Icon Images

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

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 :-)