0

I'm trying to convert a json string to a dictionary.

I came across this answer but it only works for arrays with one value.

Here is an example of a string I'm trying to turn into a swift dictionary

[
  {"value1":"Reporting for duty"},
  {"value2":"Post received"},
  {"value3":"frogg222"},
  {"value4":"Still reporting"}
]

Just to be clear, the following code does not work and will return nil with the above string.

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.data(using: String.Encoding.utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
        } catch let error as NSError {
            print(error)
        }
    }
    return nil
}
Community
  • 1
  • 1
Trevor Wood
  • 2,347
  • 5
  • 31
  • 56

0 Answers0