简体   繁体   中英

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

I'm trying to get some data from a JSON content(in my data.swift file) and assign it to "comments". Anyone know whats going wrong here and how I can fix it? Seems like a syntax issue that I'm having trouble with.

The error I am getting: 我得到的错误

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
}

It's not liking the comments = story["comments"] part.

There is an error in your code, but the error message you're seeing is incorrect and misleading due to a Swift compiler bug. The actual error message should read: AnyObject is not convertible to [String:AnyObject] .

self.story["comments"] returns an AnyObject . To assign that value to self.comments you must first typecast AnyObject to the Dictionary type [String:AnyObject] .

For example:

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

According to your own declaration, story is a [String:AnyObject] . That means that story["comments"] is an AnyObject. But comments is a [String:AnyObject] , not an AnyObject. You can't assign an AnyObject where a [String:AnyObject] is expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM