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

Jamie Baker
Jamie Baker
5,703 Points

what is wrong with this code?

this is for the stormy app. My code is as follows...

let baseURL = NSURL(string:"https://api.forecast.io/forecast/ccc2f537f3cebbe7049f67424695c2e7/") let forecastURL = NSURL(string: "37.8267,-122.423", relativeToURL: baseURL)

    let sharedSession = NSURLSession.sharedSession()
    let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
        if (error == nil)
        {   let dataObject = NSData(contentsOfURL: location)
            let weatherDic: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary!

}

I am getting two errors. for my weather dic, the error is telling me 'AnyObject? is not convertible to NSDictionary!: did you mean to use as! to force downcast'...it's essentially telling me to add the bang operator to as, but I've never been taught that before. don't know what's going on there.

the next error is telling me 'expected ',' separator' after my final curly brace at the end of the code block. really at a loss again as to why. help appreciated massively!

Jamie Baker
Jamie Baker
5,703 Points

i should note as welll that the network call isnt working as a result.

1 Answer

"did you mean to use as!" is due to an update in swift lang.

let sharedSession = NSURLSession.sharedSession()

        let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in


            if (error == nil) {

                let dataObject = NSData(contentsOfURL: location)
                let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary

                let currentWeather = Current(weatherDictionary: weatherDictionary)
                let weeklyWeather = Weekly(weatherDictionary: weatherDictionary)
                var alertWeather = WeatherAlerts(weatherDictionary: weatherDictionary)

Check out this Github project. It's built on top of the treehouse app Stormy.