类型'(String,AnyObject)'没有下标成员

时间:2016-03-22 20:05:18

标签: swift

我遇到了类似的问题,但仍然不明白为什么我的代码会出错。

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数据:

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

当我使用[[[String:AnyObject]]

错误: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.}

为什么?

2 个答案:

答案 0 :(得分:7)

原因是这个非常好奇的短语

for post in posts

问题是posts是字典(不是数组)。所以你要求循环通过字典。这是一件非常奇怪的事情。当你这样做的结果有点奇怪:每次循环,你得到一个代表一个键值对的元组

答案 1 :(得分:2)

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

let posts: [String: AnyObject] = …。这使posts成为字典。

for post in posts! {

正在迭代一个字典,所以它的类型是for post: (String, AnyObject) in …

如果您想要一组字典,那么您需要[[String: AnyObject]]

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

有了这个改变,那么

for post in posts! {

的类型为for post: [String: AnyObject] in …