![](/img/trans.png)
[英]Cannot subscript a value of [AnyObject]? with an index of type String
[英]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"]
部分。
您的代碼中存在錯誤,但由於Swift編譯器錯誤,您看到的錯誤消息不正確且具有誤導性。 實際的錯誤消息應為: AnyObject is not convertible to [String:AnyObject]
。
self.story["comments"]
返回一個AnyObject
。 要指定該值self.comments
您必須首先強制轉換AnyObject
的詞典類型[String:AnyObject]
例如:
self.comments = self.story["comments"] as! [String:AnyObject]
根據你自己的聲明, story
是[String:AnyObject]
。 這意味着story["comments"]
是一個AnyObject。 但是comments
是[String:AnyObject]
, 而不是 AnyObject。 您不能指定期望[String:AnyObject]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.