转换时变量为null

时间:2015-12-16 15:53:14

标签: ios swift casting nsnull

我有来自NSArray的可变内容:let content = application["content"]!

当我打印内容时,我有一个字符串: print(content) - > My content

但是当我想将变量转换为String:let content = application["content"]! as! String

我无法打印我的变量,因为它为null: print(content) - > Could not cast value of type 'NSNull' (0x1a0507768) to 'NSString' (0x1a0511798).

为什么?

更新:

未输出值时的数组:

{
    "application_title" = "Marina Kaye";
    "application_type" = discussions;
    "application_type_name" = Discussions;
    content =     (
                {
            content = "Le nouvel album de Marina Kaye";
            link = "?message_id=118";
        },
                {
            content = "Son album est num\U00e9ro 1 des";
            link = "?message_id=131";
        },
                {
            content = "Le nouvel album s'appel";
            link = "?message_id=126";
        }
    );
    "content_title" = "Messages utiles";
    "content_type" = "useful_messages";
}

投射价值时的数组:

{
    "application_title" = "Marina Kaye";
    "application_type" = discussions;
    "application_type_name" = Discussions;
    content = "<null>";
    "content_title" = "<null>";
    "content_type" = "usefull_messages";
}

我无法将内容强制转换为NSArray,将content_title转换为String。

我的代码:

    let applicationsArray = result["applications"]! as! NSArray

    for application in applicationsArray {

        let applicationTitle = application["application_title"]! as! String
        let applicationType = application["application_type"]! as! String
        let applicationTypeName = application["application_type_name"]! as! String
        let content = application["content"]! as! NSArray
        let contentTitle = application["content_title"]! as! String
        let contentType = application["content_type"]! as! String
        self.listApplications.append(Application(applicationTitle: applicationTitle, applicationType: applicationType, applicationTypeName: applicationTypeName, content: content, contentTitle: contentTitle, contentType: contentType))
    }

1 个答案:

答案 0 :(得分:3)

当您使用Swift编码时,您不需要旧版NSArrayNSDictionary类型。相反,这些现在是ArrayDictionary,但您甚至不必关心这一点。

要声明数组,通常在方括号中指定类型,例如[String]。对于字典,你需要这个用于键和值,用冒号分隔,例如[String: AnyObject]

从日志输出中,您有一个类型为[String: AnyObject]的词典,其中包含6个键;所有这些对象都指向String个对象,但"content"对象除外。

"content"键显然指向字典数组。这是这样写的:[[String: AnyObject]]。因此将String转换为application并不成功就不足为奇了。

以下是解析if let content = application["content"] as? [[String: AnyObject]] { for item in content { let text = content["content"] as? String let link = content["link"] as? String // do something with this data } } 字典&#34;内容&#34;:

的方法
class

我建议定义structcount()来捕获应用程序对象。您的代码将更清晰,更易于维护。