swift - 无法将“_SwiftValue”(0x1106695f8)类型的值转换为“NSArray”(0x110112598)
问题描述
我正在获取 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()
在表格视图单元格中
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 字典 never [String:AnyObject]
,它是[String:Any]
错误很明显。data["image"]
包含一个(Swifty)JSON 对象,即提到的_SwiftValue
类型。
获取返回的product
使用字典dictionaryObject
[String:Any]?
self.productsDetails.append(response["data"]["product"].dictionaryObject!)
请不要使用可怕的语法(data["image"]! as? [String])!
,例如
强制将可选项向下转换为可选项,然后强制解包。
如果它应该是可选的向下转换它有条件(data["image"] as? [String]
)或强制向下转换一次(data["image"] as! [String]
)
注意:我们鼓励您放弃 SwiftyJSON 以支持Codable
. 它是内置的并且更高效。
推荐阅读
- css - 如何防止元素重叠,分别显示?
- python - 不断检查一个元素是否在屏幕上 - Python Selenium
- r - 如何在 Rstudio 中为每日时间序列创建箱线图?
- c# - 如何比较大 JSON?
- java - 为什么同步方法只能被两个线程依次调用?
- database - 如何在数据库中查找和替换 meta_key
- javascript - PrestaShop 1.7 如何在产品页面上获取 id_product_attribute?
- bash - bash 脚本,用于从各种 datapower 框中检索 Rest api 服务列表并将内容显示到浏览器或 Excel 表
- javascript - 在加载科尔多瓦时打开系统浏览器
- python - python - 如何使用python中的mongoengine在ListField中的元素之后插入?