我正在获取 JSON 字典数据并将它们附加到 [[String:Anyobject]] 变量中,但是当我尝试放入获取的“图像”数据时。作为变量中的 [String] 数组,当我尝试将数组元素打印为 [String] 时,它打印 nil
var productsDetails = [字符串:AnyObject]
guard let response = data else {return}
if response["success"].boolValue == true , error == nil{
//cell.titleLabel.text = response["data"]["product"]["title"] as? String
self.productsDetails.append(response["data"]["product"].dictionary! as [String : AnyObject])
}
self.cartTableView.reloadData()
在表格 View 单元格中
let data = self.productsDetails[indexPath.row]
cell.titleLabel.text = "\(data["title"]!)"
cell.amountLabel.text = "\(data["price"]!)"
cell.decriptionLabel.text = "\(data["details"]!)"
let strum :[String] = (data["image"]! as? [String])! // this line is giving error
print(strum)
print(String(describing: type(of: data["image"])))
return cell
最佳答案
首先,Swift 3+ 中的 JSON 字典永远不会是 [String:AnyObject]
,它是 [String:Any]
错误很明显。 data["image"]
包含一个 (Swifty)JSON 对象,就是上面提到的 _SwiftValue
类型。
获取product
的字典使用 dictionaryObject
返回 [String:Any]?
self.productsDetails.append(response["data"]["product"].dictionaryObject!)
请不要使用像 (data["image"]! as? [String])!
这样可怕的语法这是
force downcast an optional to an optional and then force unwrap it.
如果它应该是可选的,有条件地向下转型(data["image"] as? [String]
)或强制向下转型一次(data["image"] as! [String]
)
注意:我们鼓励您放弃 SwiftyJSON,转而使用 Codable
.它是内置的,效率更高。
关于swift - 无法将类型 '_SwiftValue' (0x1106695f8) 的值转换为 'NSArray' (0x110112598),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56373789/