Cannot index a value of 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 will not allow me to compile, and if I get this error message in red:

You cannot index a value of type AnyObject with an index of type String

When you display the contents of jParams in a log using 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 JSON processing to solve these 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"] 
+6
source share
1 answer

In your editing, it looks like you are using SwiftyJSON.

If this is true, you can help the compiler find out what's in the dictionary using the SwiftyJSON dictionaryValue property:

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

Then you should have access to your values ​​without downcasting:

 let title = jParams["title"] 

because SwiftyJSON will output the correct type for the values.

+11
source

Source: https://habr.com/ru/post/987949/


All Articles