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 Network Programming with Swift 2 Modeling Forecast Data Stubbing the Data

Cagri Mehmet Calis
Cagri Mehmet Calis
5,791 Points

"Extension" problem in ViewController.swift file

When I try to write below code in ViewController.swift file, there is an error occurs. (Declaration is only valid at file scope)

extension CurrentWeather { var temperatureString: String { return "(Int(temperature))" } }

When I write this code snippet in CurrentWeather.swift file that's OK.

How can I solve this problem? Xcode Version 7.3.1

Check out this answer: https://stackoverflow.com/questions/28554231/about-declaration-is-only-valid-at-file-scope

*Also make sure to put "\" in your return statement.

    var temperatureString: String {
        return "\(Int(temperature))ΒΊ"
    }

1 Answer

The extension declaration should be right after the import statement and before the class ViewController: UIViewController... declaration. This way the scope of the extension is broad enough to reach the entire project and not just the ViewController file.