我有来自服务器的数据
[
{
"id": 1,
"name": "16",
"children": "",
"products": [
{...},
{...}
]
},
{
"id": 2,
"name": "17",
"children": "",
"products": [
{...},
{...}
]
}
]
所以我将其保存为[[String: Any]]
,而Any
的保存是因为这些值可以有Int
,String
或Dict
。
关键是“子级”键可以是NSConstantstring
,可以强制转换为String
,也可以是NSArray
,也可以强制转换为[[String: Any]]
。因此,我需要找到一种方法来检测该值的类型。但是我尝试过的所有方法都导致了错误。
我该如何解决?
UPD 没有太多代码)
内部alamofire响应:
let data = responseJSON.result.value! as! [String: Any]
let subCategory = data["children"] as! [[String: Any]]
//check
for item in subCategory {
print(type(of: item["children"]!))//__NSArrayI or __NSCFConstantString
}
如果我尝试类似print(type(of: item["children"] as! String))
的操作,如果有String
,它会打印__NSCFConstantString
,但如果没有,则会崩溃,并显示错误Could not cast value of type '__NSArrayI' (0x10934fe48) to 'NSString' (0x1083e8568)
UPD 2 数据没有问题,所有数据都可以正确解析并保存,并且可以正确打印出来
答案 0 :(得分:0)
您可以将字典中的值强制转换为所需的类型:
if let string = dictionary["children"] as? String {
// Do something with string
} else if array = dictionary["children"] as? [Any] {
// Do something with array
}