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

标签 ios swift dictionary anyobject

我在“词典”上创建了一个扩展来帮助我解析 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 {

我收到一条警告,说“检查可选值时使用了‘AnyObject’类型的非可选表达式”

我该如何解决这个问题?

最佳答案

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

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

关于ios - 类型为 'AnyObject' 的非可选表达式用于检查可选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39799471/

相关文章:

ios - 我如何使用多个文件在 viewController 中访问它们?

python - 字典列表检查键 :value

iOS NSNumberFormatter 货币代码是如何工作的?

iphone - 通过 RTP/RTSP 的 H.264 (iPhone)

ios - iOS 中的 Crashlytics 不会继续处理 Fabric 应用程序中的 "Build Your Project"

ios - Swift 4 - 以编程方式在 AutoLayout UITableViewCell 中切碎多行标签

ios - NSStream 委托(delegate) NSStreamEventHasBytesAvailable 未被调用

swift - 错误 : conditional compilation flags must be valid Swift identifiers (rather than '-sdk' )

Java DynamoDBMapper。映射属性值 'M'

python - Numpy 通过字典进行广播