J.Arji
J.Arji

Reputation: 661

Type '(String, AnyObject)' has no subscript members

I've been through similar questions but still do not understand why my code is throwing an error.

let posts = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as?[String: AnyObject]
                print(posts)

                for post in posts! {
                    var postObject:Post?
                    if let id = post["ID"] as? Int , let name = post["Country_Name"]as? String{ //Type '(String, AnyObject)' has no subscript members
                        postObject = Post(ID: id, Name: name)
                        self.CountryId.append(id)
                    }
                    self.CountrySelected.append(postObject!)

json data :

[
  {
    "$id": "1",
    "ID": 1,
    "Country_Name": "sample string 2"
  },
  {
    "$ref": "1"
  }
]

when i use [[[String: AnyObject]]

error : Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

why?

Upvotes: 1

Views: 8446

Answers (2)

Jeffery Thomas
Jeffery Thomas

Reputation: 42598

let posts = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as?[String: AnyObject]

is let posts: [String: AnyObject] = …. This makes posts a dictionary.

for post in posts! {

is iterating a dictionary, so it's type is for post: (String, AnyObject) in …

If you want an array of dictionaries, then you need [[String: AnyObject]].

let posts = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as?[[String: AnyObject]]

With that change, then

for post in posts! {

has the type for post: [String: AnyObject] in ….

Upvotes: 2

matt
matt

Reputation: 535989

The reason is this very curious phrase

for post in posts

The problem is that posts is a dictionary (not an array). So you are asking to cycle through a dictionary. That is a very strange thing to do. And the result when you do it is a little strange: each time through the cycle, you get a tuple representing one key-value pair.

Upvotes: 7

Related Questions