Reputation: 3249
I have parsed a JSON array and extracted an NSDictionary and from this have extracted a String variable and successfully passed this via a segue to my next view. When I try to do the same with an integer the app crashes...
This is my code:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "genreSegue" {
println("genreSegue")
let indexPath = self.tableView.indexPathForSelectedRow()
println("row: \(indexPath.row)")
var bookView:BookViewController = segue.destinationViewController as BookViewController
if let genres = self.genreList as? [NSDictionary] {
var item = genres[indexPath.row]
println("segueItem: \(item)")
let title:String = item["title"] as String
let genreId:Int = item["id"] as Int // this line crashes the app
let genreId:NSNumber = item["id"] as NSNumber // this version also crashes
println("title: \(title)")
bookView.genreTitle = item["title"] as String
//bookView.genreId = item["id"] as Int // so I can't test this line
}
}
}
Here is the console output:
genreSegue
row: 1
segueItem: {
id = 2;
records = 1;
selfLink = "http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/id/2";
title = Biography;
}
title: Biography
Here is the error on thread 1: libswift_stdlib_core.dylib`swift_dynamicCastObjCClassUnconditional:
Here is the original json data:
http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list
Here is my app source code:
https://github.com/marktyers/ios_bookshop_client
I don't see how the string variable works but not the int. Any ideas?
Upvotes: 2
Views: 6962
Reputation: 3485
The problem is that the number you are looking for is not a number in the JSON, it's a String. So try this:
let genreId = (item["id"] as String).toInt() // This casts the String to an Integer
// Note that this is not Int but Int?
Here you see thats a string:
Upvotes: 3