I've just started with Swift and I'm trying to loop through a json response and add it to a dictionary. But nothing seems to be added, not sure what the problem is maybe scope? I'm using SwiftyJSON. In my code i'm able to print the news title within the for loop like so json[0]["title"]
etc. But when I print the values of the dictionary nothing is ouputted.
// news dictionary
var newsDictionary = [String] ()
override func viewDidLoad() {
super.viewDidLoad()
// get news feed url
let url = NSURL(string: baseUrl + "news")
// create session
let session = NSURLSession.sharedSession()
// create data task
let task = session.dataTaskWithURL(url!, completionHandler: { (data: NSData!, response:NSURLResponse!,
error: NSError!) -> Void in
// convert data object to json
let json = JSON(data: data)
for var i = 0; i < json.count; ++i {
// get news title from json object
var title = json[i]["title"].string
// add to dictionary
self.newsDictionary.append(title!)
}
})
for news in newsDictionary{
println(news)
}
// execute call
task.resume()
// Do any additional setup after loading the view.
}