无法使用 'String' 类型的索引下标“[String : AnyObject]”类型的值

Cannot subscript a value of type '[String : AnyObject]' with an index of type 'String'

我正在尝试从 JSON 内容(在我的 data.swift 文件中)获取一些数据并将其分配给 "comments"。任何人都知道这里出了什么问题以及我该如何解决?似乎是我遇到的语法问题。

我得到的错误:

import UIKit

class CommentsTableViewController: UITableViewController {

var story = [String:AnyObject]()
var comments = [String:AnyObject]()

override func viewDidLoad() {
    super.viewDidLoad()

    comments = story["comments"]

    tableView.estimatedRowHeight = 140
    tableView.rowHeight = UITableViewAutomaticDimension
}

不喜欢 comments = story["comments"] 部分。

根据你自己的声明,story是一个[String:AnyObject]。这意味着 story["comments"] 是一个 AnyObject。但是 comments[String:AnyObject] 不是 AnyObject。您不能在需要 [String:AnyObject] 的地方分配 AnyObject。

您的代码中存在错误,但由于 Swift 编译器错误,您看到的错误消息不正确且具有误导性。实际错误消息应为:AnyObject is not convertible to [String:AnyObject].

self.story["comments"] returns 一个 AnyObject。要将该值分配给 self.comments,您必须首先将 AnyObject 类型转换为字典类型 [String:AnyObject]

例如:

self.comments = self.story["comments"] as! [String:AnyObject]