swift - 无法将类型 '_SwiftValue' (0x1106695f8) 的值转换为 'NSArray' (0x110112598)

标签 swift dictionary swifty-json

我正在获取 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/

相关文章:

swift - 无法从 IOS 11、swift 4 中的服务器接收远程通知?

swift - 单击 StatusBar 项目时弹出一个 View

ios - 如何将字典的字典保存到 UserDefaults [Int :[Int:Int]]?

java - 重新解析 Map 的干净方法

ios - 如何在 swift 4 中通过 SwiftyJson 和 Alamofire 创建多个按钮?

swift3 - 无法使用 'JSON' 类型的索引为 'STRING' 类型的值添加下标

Swift AnyClass 引用 Class 实例还是只是 Type?

ios - 在 UISearchController Swift 中将标题与图像名称匹配

swift - 遍历字典并检查每个值类型

ios - 在 iPhone 上调试以不同于模拟器的方式解析 JSON 值