NSDictionary in Swift: can't index value of type "AnyObject"? with an index of type 'Int'

So, I'm trying to parse some data in JSON using swift. below is my code

var jsonResult:NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary println(jsonResult) 

The above code will return something like this

 { count = 100 subjects = ( { alt = "....." name = "....." }, { alt = "....." name = "....." }, ...... ) } 

Then I try to access all topics using jsonResult["subjects"] , so good. But when I try to access a single subject, for example jsonResult["subjects"][0] , Xcode gives me an error: Cannot subscript a value of type 'AnyObject?' with an index of type 'Int' Cannot subscript a value of type 'AnyObject?' with an index of type 'Int' Can someone help me with this?

+6
source share
3 answers

When you index a dictionary, as in jsonResult["subjects"] , you get an optional one. You need to expand the option. Moreover, since this dictionary comes from JSON, Swift does not know what it contains: it is typed as AnyObject, so does Swift describe optional as AnyObject? . That way, you also tell Swift which type of object it really is β€” it’s a set of dictionaries, and you need to tell Swift, or you won’t be able to index it with [0] .

You can do both of these things in one move, for example:

 if let array = jsonResult["subjects"] as? [[NSObject:AnyObject]] { let result = array[0] // ... } 

If you are very, very confident in your land, you can force the casting to be expanded and reduced to one line, for example:

 let result = (jsonResult["subjects"] as! [[NSObject:AnyObject]])[0] 

But I can not recommend it. Too many ways to do it wrong.

+7
source

With Swift 2, at least you can do with jsonResult ["subject"] like! [AnyObject]

 let data = try NSJSONSerialization.JSONObjectWithData(textData!, options: NSJSONReadingOptions.AllowFragments) let results = data["results"] as! [AnyObject] let first = results[0] 
+2
source

You should try

  var jsonResult:NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary let subjhectarry : NSArray = jsonResult["subjects"] as! NSArray let yourFirstObj : NSDictionary = subjhectarry[0] as! NSDictionary 

Help you.

0
source

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


All Articles