Swift: How to convert string to dictionary

15,584

Solution 1

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.

Solution 2

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
}
Share:
15,584
Display Name
Author by

Display Name

Updated on June 07, 2022

Comments

  • Display Name
    Display Name almost 2 years

    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