unexpectedly found nil when unpacking an optional value when converting JSON Array

advertisements

while I try to convert Json String to Dictionary it gives me fatal eror: unexpectedly found nil while unwrapping an Optional value.

self.res = Jsn.convertStringToDictionary(self.sub)!

sub = [{"CityId":6,"CityName":"Ankara"},{"CityId":34,"CityName":"İstanbul"}]

And the function is:

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        do {
            return try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [String:AnyObject]
        } catch {
            print(error)
        }
    }
    return nil
}

Can you help me with the problem. Thank you in advance!


You should convert it to [[String:AnyObject]] instead of [String:AnyObject] because it is array of dictionaries.

Try using

return try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [[String:AnyObject]]