【问题标题】:Could not cast value of type '_SwiftValue' (0x1106695f8) to 'NSArray' (0x110112598)无法将“_SwiftValue”(0x1106695f8)类型的值转换为“NSArray”(0x110112598)
【发布时间】:2019-10-15 20:18:52
【问题描述】:

我正在获取 JSON 字典数据并将它们附加到 [[String:Anyobject]] 变量中,但是当我尝试放入获取的“图像”数据时。作为变量中的 [String] 数组,当我尝试将数组元素打印为 [String] 时,它会打印 nil

var productsDetails = [String: 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 dictionary swifty-json


    【解决方案1】:

    首先,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])! 这样的可怕语法

    强制将可选项向下转换为可选项,然后强制解包。

    如果它应该是可选的向下转换(data["image"] as? [String])或强制向下转换一次(data["image"] as! [String])

    注意:我们鼓励您放弃 SwiftyJSON 以支持 Codable。它是内置的并且更高效。

    【讨论】:

    • 非常感谢@vadian .. 使用 dictionaryObject 解决了问题 .. 您的解决方案很干净,我会处理我的语法选择。作为新手。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2015-08-29
    • 2020-03-26
    • 1970-01-01
    相关资源
    最近更新 更多