无法使用索引类型为“String”的类型'[String:AnyObject]'下标值 [英] Cannot subscript a value of type '[String : AnyObject]' with an index of type 'String'

查看:3180
本文介绍了无法使用索引类型为“String”的类型'[String:AnyObject]'下标值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

它不喜欢 comments = story [注释] part。

推荐答案

您的代码中有错误,但错误消息是您由于Swift编译器错误,我看到的是不正确和误导。实际的错误消息应为: AnyObject不能转换为[String:AnyObject]

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] 返回 AnyObject 。要将该值分配给 self.comments ,您必须首先将 AnyObject 强制转换为字典类型 [字符串: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].

例如:

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

这篇关于无法使用索引类型为“String”的类型'[String:AnyObject]'下标值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆