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

时间:2019-05-30 07:38:40

标签: swift dictionary swifty-json

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

var productsDetails = [String:AnyObject]

:on

在表格视图单元格

            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()

1 个答案:

答案 0 :(得分: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。它是内置的,效率更高。

相关问题