Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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