I created an extension on 'Dictionary' to help me parse JSON. The method below helps me do this:
func toJSONString() -> String? {
if let dict = self as? AnyObject {
if let data = try? JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions(rawValue: 0)) {
if let json = String(data: data, encoding: String.Encoding.utf8) {
return json
}
}
}
return nil
}
The issue occurs on this line:
if let dict = self as? AnyObject {
I get a warning saying "Non-optional expression of type 'AnyObject' used in a check for optionals"
How do I go about solving this issue?
self
, you already know it's a dictionary. Just passself
directly to theJSONSerialization.data(...)
function. – Keldaif let
can not be used. – Latoshalatouche