AnyObject to [String:[String:String]]崩溃而没有错误

时间:2016-09-19 08:51:07

标签: swift swift3

说明

我正在尝试将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
       }
   }

2 个答案:

答案 0 :(得分:2)

尝试转换[String:[String:String]],如下所示。

  1. AnyObject as [Any: [String: Any]],如果您不确定dic键的类型(1,2,3等)。
  2. AnyObject as [String: [String: Any]]如果您确定键(1,2,3等)是字符串。
  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 = ""
}