转换时变量为空

Variable is null when cast

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

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

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

我无法打印我的变量,因为它是空的: 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 到字符串。

我的代码:

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

当您在 Swift 中编码时,您不需要遗留的 NSArrayNSDictionary 类型。相反,它们现在是 ArrayDictionary,但您甚至不必关心这些。

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

从您的日志输出中,您有一个 [String: AnyObject] 类型的字典,有 6 个键;它们都指向 String 个对象,除了 "content" 个对象。

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

下面是解析 application 字典的 "content" 的方法:

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
   }
}

我建议定义一个 classstruct 来捕获应用程序对象。您的代码将更加清晰和易于维护。