Non-optional expression of type 'AnyObject' used in a check for optionals

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:

  • Swift how to sort dict keys by byte value and not alphabetically?
  • How to add values in swift dictionary dynamically
  • Comparing UIColors fails, but hashes are equal?
  • Swift NSUserDefaults not saving Dictionary?
  • C++ / Objective-C++ - How can I store a C++ variable in an NSDictionary?
  • Remove nested key from dictionary
  • 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?

    2 Solutions Collect From Internet About “Non-optional expression of type 'AnyObject' used in a check for optionals”

    Simply remove the line that causes warning from your code and pass self as is for the JSONSerialization function. This should work without any issues:

    extension Dictionary {
    
        func toJSONString() -> String? {
            if let data = try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0)) {
                if let json = String(data: data, encoding: String.Encoding.utf8) {
                    return json
                }
            }
    
            return nil
        }
    }
    

    Your are unwrapping something that was already unwrapped. Take a look at this stackoverflow post