1

我有一个来自 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))
    }
4

1 回答 1

3

当你在 Swift 中编码时,你不需要 legacyNSArrayNSDictionarytypes。相反,这些现在是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
   }
}

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

于 2015-12-16T17:04:36.347 回答