Swift:如何将字符串转换为字典 [英] Swift: How to convert string to dictionary

查看:86
本文介绍了Swift:如何将字符串转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,我将其转换为字符串以将其存储在数据库中.

I have a dictionary which i convert to a string to store it in a database.

        var Dictionary =
    [
        "Example 1" :   "1",
        "Example 2" :   "2",
        "Example 3" :   "3"
    ]

我使用

Dictionary.description

获取字符串.

我可以将其完美地存储在数据库中,但是当我读回它时,显然是一个字符串.

I can store this in a database perfectly but when i read it back, obviously its a string.

"[Example 2: 2, Example 3: 3, Example 1: 1]"    

我想将其转换回我可以对其进行评估

I want to convert it back to i can assess it like

Dictionary["Example 2"]

我该怎么做?

谢谢

推荐答案

不能保证description文本在各个SDK版本之间都是稳定的,因此我不会依赖它.

What the description text is isn't guaranteed to be stable across SDK versions so I wouldn't rely on it.

您最好的选择是将JSON用作 NSJSONSerialization 的中间格式一个>.从字典转换为JSON字符串然后返回.

Your best bet is to use JSON as the intermediate format with NSJSONSerialization. Convert from dictionary to JSON string and back.

这篇关于Swift:如何将字符串转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆