首页 > 解决方案 > 无法将“_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

标签: swiftdictionaryswifty-json

解决方案


首先,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. 它是内置的并且更高效。


推荐阅读