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

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.