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

J.A*_*rji 1 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!)
Run Code Online (Sandbox Code Playgroud)

json数据:

[
  {
    "$id": "1",
    "ID": 1,
    "Country_Name": "sample string 2"
  },
  {
    "$ref": "1"
  }
]
Run Code Online (Sandbox Code Playgroud)

当我使用[[[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.}

为什么?

mat*_*att 7

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

for post in posts
Run Code Online (Sandbox Code Playgroud)

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