我正在尝试将AnyObject
从[String: AnyObject]
转换为[String: [String: String]]
,但只是崩溃而没有任何错误。
//where my dict is the [String: AnyObject]
if let data = dict["data"]{
//We enter here
print(data)
//Crashes here.. because of conversion
for (_, item) in data as! [String: [String: String]]{
//Do stuff here
}
}
以下是数据打印:
{
1 = {
col = "#006666";
date = "2016-09-01";
desc = "<null>";
img = "1.png";
tit = "title here";
url = "id=1";
};
2 = {
col = "#006666";
date = "2016-07-01";
desc = "<null>";
img = "2.png";
tit = "title here";
url = "id=2";
};
3 = {
col = "#006666";
date = "2016-10-01";
desc = "<null>";
img = "3.png";
tit = "title here";
url = "id=3";
};
4 = {
col = "#006666";
date = "2016-06-01";
desc = "<null>";
img = "4.png";
tit = "title here";
url = "id=4";
};
}
为什么我无法将AnyObject
转换为[String: [String: String]]
甚至[Int: [String: String]]
?
将其转换为[String: [String: AnyObject]]
让我进入循环。然后,当我尝试处理desc
时,它崩溃了:
//In the loop
if let description = item["desc"]{
//Should enter here.. but it doesn't...
if (description.isEqual(NSNull.self)){
fotmItem.description = ""
} else {
//enters here and attempts to convert "<null>" to string and crashes
fotmItem.description = description as! String
}
}
答案 0 :(得分:2)
尝试转换[String:[String:String]],如下所示。
AnyObject as [Any: [String: Any]]
,如果您不确定dic键的类型(1,2,3等)。AnyObject as [String: [String: Any]]
如果您确定键(1,2,3等)是字符串。因此,只要您不了解字典值数据类型(Int或String或Null等),[String: Any]
就会很有用。
例如:
if let data = dict["data"] as? [String: [String: Any]]{
for (_, item) in data{
//Do stuff here
}
}
处理desc的更新:
if let description = item["desc"] as? String, description != "<null>"{
fotmItem.description = description
}else{
fotmItem.description = ""
}
注意:语法在Swift 3.0中
答案 1 :(得分:1)
您应该将item["desc"]
与NSNull()
进行比较,而不是NSNull.self
。
替换此
if (description.isEqual(NSNull.self)){
与
if (description.isEqual(NSNull())){
另一种方法是尝试将其转换为String
if let description = item["desc"] as? String {
fotmItem.description = description
} else {
fotmItem.description = ""
}