cannot subscript a value of type NSDictionary with an index of type string

BorjaCin picture BorjaCin · May 22, 2015 · Viewed 14k times · Source
    var url: NSURL = NSURL(string: urlPath)!

    var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
    request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
    request.HTTPMethod = "GET"

    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error:nil)!

    var err: NSError
    println(dataVal)


    //var jsonResult : NSDictionary?
    var jsonResult  = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary

    println("Synchronous  \(jsonResult)")
    jsonResult["records"] 

Here is where the error happens, I just want to take one value from my jsonResult, which is printed correctly at the console.

Answer

Amit89 picture Amit89 · May 22, 2015

You are typecasting the jsonResult as NSDictionary, instead use [String:AnyObject]

If you are using NSDictionary, you should use valueForKey(key) or objectForKey(key) methods of NSDictionary to get value for the key.

    var url: NSURL = NSURL(string: urlPath)!
    var err: NSError?

        var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
        request.HTTPMethod = "GET"

        var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error:nil)!

        var err: NSError
        println(dataVal)


        //var jsonResult : NSDictionary?
        var jsonResult:AnyObject?  = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableLeaves, error: &err)  

        println("Synchronous  \(jsonResult)")
        if let result = jsonResult as? [String: AnyObject] {
           if let oneValue = result["records"] as? String { //Here i am considering value for jsonResult["records"] as String, if it other than String, please change it.
             println(oneValue)
           }
       }