swift - 常量 json 推断有 'AnyObject' ,这可能是意外的

标签 swift

我正在使用下面的代码进行 json 解析,但编译器提示警告“Constant json inferred to have 'AnyObject', which may be unexpected”。我将如何解决警告?我的 json 响应可能是 json 数组或字典。如何以通用方式实现它?

if let json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &jsonError) {
}

最佳答案

试试这个:

let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: nil)
if let j = json as? Array<AnyObject> {
    //this is an array
} else if let j = json as? Dictionary<String, AnyObject> {
    //this is a dict
}

关于swift - 常量 json 推断有 'AnyObject' ,这可能是意外的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27291629/

相关文章:

ios - 使用 Swift PFIdResultBlock 错误解析云

ios - iOS 中的导航栏按钮可见性问题

ios - swift ;如何在点击推送通知时打开 Safari 而无需打开应用程序?

swift - 确定 WatchOS 2 应用程序何时打开的最佳方法是什么?

ios - 当用户在文本字段中键入 @ 符号时,有没有办法为电子邮件添加域建议

ios - 在 Alamofire 中发送 JSONObject

ios - 更改了 rootViewController 但旧 rootViewController 的 View 仍在 View 层次结构中

ios - Firebase 数据库 - 检查现有用户

ios - 使用 Swift 的 iOS 代码结构,所有代码放在哪里?

ios - 在 Swift 4 中使用 KeyEnumerators