'AnyObject' 类型的非可选表达式用于检查可选值

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

我在 'Dictionary' 上创建了一个扩展来帮助我解析 JSON。下面的方法可以帮助我做到这一点:

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
}

此行出现问题:

if let dict = self as? AnyObject {

我收到一条警告说 "Non-optional expression of type 'AnyObject' used in a check for optionals"

我该如何解决这个问题?

您正在打开已经打开的东西。看看这个

只需从您的代码中删除导致警告的行,然后像 JSONSerialization 函数一样传递 self。这应该没有任何问题:

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