Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to convert string to dictionary

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"
    ]

And i use the

Dictionary.description

to get the string.

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"]

How do i go about doing that?

Thanks

like image 788
Display Name Avatar asked Jan 08 '23 16:01

Display Name


2 Answers

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

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

like image 163
gregheo Avatar answered Jan 21 '23 21:01

gregheo


I created a static function in a string helper class which you can then call.

 static func convertStringToDictionary(json: String) -> [String: AnyObject]? {
    if let data = json.dataUsingEncoding(NSUTF8StringEncoding) {
        var error: NSError?
        let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String: AnyObject]
        if let error = error {
            println(error)
        }
        return json
    }
    return nil
}

Then you can call it like this

if let dict = StringHelper.convertStringToDictionary(string) {
   //do something with dict
}
like image 41
Jeremiah Avatar answered Jan 21 '23 23:01

Jeremiah