我正在使用这个库来解析返回数组的 API 端点:https://github.com/SwiftyJSON/SwiftyJSON
我正在抓取一个从 JSON 响应中获取的数组,并试图将它输入到一个表中。
在我的 View Controller 中的类被声明之后,我有
var fetched_data:JSON = []
我的 viewDidLoad 方法内部:
let endpoint = NSURL(string: "http://example.com/api")
let data = NSData(contentsOfURL: endpoint!)
let json = JSON(data: data!)
fetched_data = json["posts"].arrayValue
为了喂饱 table ,我有:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell1")! as UITableViewCell
cell.textLabel?.text = self.fetched_data[indexPath.row]
return cell
}
我在尝试设置单元格文本标签时遇到此错误:
Cannot subscript a value of a type ‘JSON’ with an index type of ‘Int’
我如何正确地执行此操作并使其正常工作?
最佳答案
您正在将 fetched_data
声明为 JSON
var fetched_data:JSON = []
但您正在为其分配 Array
:
fetched_data = json["posts"].arrayValue
让我们将类型更改为 AnyObject
的数组:
var fetched_data: Array<AnyObject> = []
然后分配应该是这样的(我们有 [AnyObject]
所以我们需要转换):
if let text = self.fetched_data[indexPath.row] as? String {
cell.textLabel?.text = text
}
编辑:您还需要记住分配正确的 Array
,方法是执行 arrayObject
而不是 arrayValue
:
fetched_data = json["posts"].arrayObject
关于ios - JSON 数组 Swift 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34053466/