Hot to Fix Type'NSFastEnumerationIterator.Element'(又名'Any')没有下标成员

时间:2016-11-11 21:00:34

标签: json swift3 xcode8.1 nsfastenumeration

试图获得帖子的'标题','内容',类别'标题'和&这个JSON的作者姓名。得到错误Type 'NSFastEnumerationIterator.Element' (aka 'Any') has no subscript members。控制台中的打印帖子工作正常,但在尝试获取帖子的标题时收到错误。请帮忙。 JSON& Swith Code是

JSON

{  
   "status":"ok",
   "count":1,
   "count_total":44,
   "pages":44,
   "posts":[  
      {  
         "id":87,
         "url":"http://www.website.com/blogs/my first blog/",
         "title":"My First Blog",
         "content":"blog content",
         "date":"2015-04-06 22:42:12",
         "modified":"2015-12-26 00:45:09",
         "categories":[  
            {  
               "id":45,
               "title":"Trip",
               "description":"",
               "post_count":21
            }
         ],
         "author":{  
            "id":1,
            "name":"admin",
            "url":"",
            "description":"hello"
         }
      }
   ]
}

Swift Code

            if let blogContent = data {

                do {

                    let jsonResult = try JSONSerialization.jsonObject(with: blogContent, options: JSONSerialization.ReadingOptions.mutableContainers)

                    if let items = jsonResult as? [NSString:Any] {

                        //print(items)

                        let item = items["posts"] as! NSArray

                        for post in item {

                            print(post)

                            print(post["title"])

                        }

                    }
                } catch {

                    print("JSON processing failed.")
                }

            }

1 个答案:

答案 0 :(得分:1)

搞定了。这是工作代码。希望它可以帮助有同样问题的人。谢谢:))

if let blogContent = data {

                do {

                    let jsonResult = try JSONSerialization.jsonObject(with: blogContent, options: JSONSerialization.ReadingOptions.mutableContainers)

                    if let items = jsonResult as? [String: AnyObject] {

                        if let item = items["posts"] as? NSArray {

                            for posts in item {

                                if let post = posts as? [String: AnyObject] {

                                    print(post["title"]!)

                                    let categories = post["categories"] as! NSArray

                                    for category in categories {

                                        if let categ = category as? [String: AnyObject] {

                                            print(categ["title"]!)

                                        }
                                    }

                                    let author = post["author"] as! [String: AnyObject]

                                    print(author["name"]!)

                                }

                            }

                        }