Anton Grigoryev
Anton Grigoryev

Reputation: 1219

Unable to iterate through array

I'm trying to get some data from the local server while parsing json. In a view controller I access local Ruby on Rails server:

override func viewDidLoad() {
    super.viewDidLoad()

    var url = NSURL(scheme: "http", host: "0.0.0.0:3000", path: "/api/search?query=auto")
    var request = NSURLRequest(URL: url)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {(data, response, error) in
    var data1: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println(data1)
        println(data1["companies"])
        var companies = data1["companies"] as NSArray
        for company: AnyObject in companies {
            println(company)
        }
    }
    task.resume()
}

println(data1) returns:

{
    companies = "[{\"alias\":\"02-avtomoyka-tulybaev-r-t\",\"id\":45693},{\"alias\":\"1001-zapchast-internetmagazin-avtotovarov\",\"id\":42621}]";
}

With println(data1["companies"]), I've got array of objects in the console:

[{"alias":"02-avtomoyka-tulybaev-r-t","id":45693},{"alias":"1001-zapchast-internetmagazin-avtotovarov","id":42621}]

Then, when I'm trying to iterate through that array, the app crashes. What am I doing wrong? It stucks with no errors in the console, but (lldb) and EXC_BREAKPOINT(code=EXC_I386_BPT, subcode 0x0) in Tread 6

PS: Also Xcode throws the compiler issue Constant 'company' inferred to have type 'AnyObject', which may be unexpected at for company in companies { string. How can I handle it?

Upvotes: 0

Views: 416

Answers (1)

Literphor
Literphor

Reputation: 498

Instead of var companies = data1["companies"] as NSArray try var companies = data1["companies"].allValues;

The problem is data1["companies"] is a dictionary and can't be implicitly converted to an NSArray. The compiler doesn't catch this because data1["companies"] is stored in NSDictionary as AnyObject and will allow you to cast it to any subclass.

Upvotes: 1

Related Questions