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

我的梦境 提交于 2019-12-12 10:35:38

问题


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?


回答1:


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
    }
}



回答2:


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



来源:https://stackoverflow.com/questions/39799471/non-optional-expression-of-type-anyobject-used-in-a-check-for-optionals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!