Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot subscript a value of a type AnyObject, in Swift

I have this line of code, and I want to extract the "title" key:

var title = jParams["title"] as! String

However it wont let me compile, and if I get this error message in red:

Cannot subscript a value of a type AnyObject with an index of type String

When show the contents of jParams in the log with println(jParams) I get the following content:

INCOMING LIST PARAMETERS (jParameters)
Optional({
    title = "Example List";
    values =     (
                {
            id = 1;
            name = "Line 1";
        },
                {
            id = 2;
            name = "Line 2";
        },
                {
            id = 3;
            name = "Line 3";
        }
    );
})

I am new to Swift so I am not familiar with the details of handling JSON to deal with these type of problems. What could be wrong?

//jParams comes from a JSON server response
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
            if data != nil {
                var jdata = JSON(data: data!)
                var jParams=jdata["responseData"]["extraData"]["params"]
like image 735
Josh Avatar asked May 26 '15 15:05

Josh


1 Answers

In your edit it looks like you're using SwiftyJSON.

If that is indeed the case, you can help the compiler to know what's in the dictionary by using SwiftyJSON's dictionaryValue property:

let jParams = jdata["responseData"]["extraData"]["params"].dictionaryValue

Then you should be able to access your values without downcasting:

let title = jParams["title"]

because SwiftyJSON will have inferred the right type for the values.

like image 99
Eric Aya Avatar answered Nov 10 '22 21:11

Eric Aya