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.
我试图从JSON内容(在我的数据中)获取一些数据。并将其分配给“评论”。有人知道这里出了什么问题吗?似乎是我遇到的语法问题。
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.
它不喜欢评论=故事[评论]部分。
2 个解决方案
#1
22
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]
.
您的代码中有一个错误,但是由于Swift编译错误,您看到的错误消息是错误的,并且具有误导性。实际的错误消息应该是:AnyObject不能转换为[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]
.
自我。("评论")返回一个AnyObject故事。要将该值赋值给self.comments,您必须首先将AnyObject类型转换为Dictionary类型[String:AnyObject]。
For example:
例如:
self.comments = self.story["comments"] as! [String:AnyObject]
#2
0
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.
根据您自己的声明,story是一个[String:AnyObject]。这意味着故事(“评论”)是一个任何对象。但是注释是一个[String:AnyObject],而不是AnyObject。您不能在期望使用[String:AnyObject]的地方分配AnyObject。
#1
22
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]
.
您的代码中有一个错误,但是由于Swift编译错误,您看到的错误消息是错误的,并且具有误导性。实际的错误消息应该是:AnyObject不能转换为[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]
.
自我。("评论")返回一个AnyObject故事。要将该值赋值给self.comments,您必须首先将AnyObject类型转换为Dictionary类型[String:AnyObject]。
For example:
例如:
self.comments = self.story["comments"] as! [String:AnyObject]
#2
0
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.
根据您自己的声明,story是一个[String:AnyObject]。这意味着故事(“评论”)是一个任何对象。但是注释是一个[String:AnyObject],而不是AnyObject。您不能在期望使用[String:AnyObject]的地方分配AnyObject。