有没有办法将key=value格式的字符串转换成swift中的字典?

有没有办法将key=value格式的字符串转换成swift中的字典?,swift,dictionary,Swift,Dictionary,我有一个字符串,比如: { c = type3; com = posss; g = 40111; m = "xxxx"; } 我需要把它解析成字典。每次响应键都不同。期望是这样的: let dictionary = ["c": "type3", "com": "posss", "g": "40111", "m&qu

我有一个字符串,比如:

{
    c = type3;
    com = posss;
    g = 40111;
    m = "xxxx";
}
我需要把它解析成字典。每次响应键都不同。期望是这样的:

let dictionary = ["c": "type3", "com": "posss", "g": "40111", "m": "xxxx"]

有什么想法吗?谢谢

回答您的问题,这是OpenStep格式

如果您这样做:

let dictionary = ["c": "type3", "com": "posss", "g": "40111", "m": "xxxx"]
print("dictionary: \(dictionary as! NSDictionary)")
这就是你得到的格式。 基本上,这就是如何打印
NSArray
/
NSDictionary
,即“Objective-C”属性列表(内部调用
description
方法)

现在,有一种方法可以通过
PropertyListSerialization
将其取回(毕竟.pbxcodeproj就是这种格式,Xcode必须读回):

let rawDataStr = """
{
    c = type3;
    com = posss;
    g = 40111;
   m = "xxxx";
}
"""

let rawData = Data(rawDataStr.utf8)
var format: PropertyListSerialization.PropertyListFormat = .openStep
do {
    let serialized = try PropertyListSerialization.propertyList(from: rawData, options: [], format: &format)
    print(serialized) //By default, it's a NSDictionary, so you'll get the same output, note that the order of the item may change
    print(serialized as? [String: Any])
} catch {
    print("Error: \(error)")
}
输出:

$>{
    c = type3;
    com = posss;
    g = 40111;
    m = xxxx;
}
$>Optional(["com": posss, "c": type3, "m": xxxx, "g": 40111])

但是


你是怎么得到这个值的?通常,这意味着有人给了你一本
NSDictionary
描述
,而不是给你一本
NSDictionary
的参考。一旦你弄清楚谁是罪魁祸首,你就避免了这种转变,因为你把
NSDictionary
改成
NSString
,你又把
NSString
改成了
NSDictionary
(可能有点过火,不是吗?

你肯定试过了。所以这不是一个免费的代码编写网站。如果你没有表现出至少一些(研究)的努力,你很可能在这里得到一个答案。你为什么把它作为一个字符串?它似乎是一本
NSDictionary
的印刷品。你怎么知道的?可以通过
PropertyListSerialization
PropertyListSerialization.PropertyListFormat
将其取回,但通常情况下,如果您的应用程序中有这些数据,您会出错。您使用的是
说明
,您应该在其中传递实际值。那么解释一下你是如何得到它的。@Larme这是服务器端的响应。我没有其他选择。“你为什么说我没有做研究?”因为你没有显示任何内容?JSON和OpenStep格式不仅仅是“:”到“=”。看到双引号“失踪”,有时等,我给出了一个解决方案,并建议“修复”上游的问题,仅此而已。这仍然是一个价值观,所以建议,而不仅仅是“回应”没有事后诸葛亮。谢谢。不是。正如我在上面回答的,这确实是遗留问题,谢谢你的回答。我试试看。