类型'任何'没有下标成员

时间:2017-02-03 06:45:16

标签: swift

当我转换为swift 3时,它的说法类型没有下标的成员。

let dataDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
let accessToken = dataDictionary["access_token"] as! AnyObject?

我尝试了许多可能性,但没有奏效。

2 个答案:

答案 0 :(得分:0)

JSONSerialization.jsonObject(with:options:)的返回类型为Any,不允许下标。您必须使用显式类型转换为下标。如果您尝试将数据转换为[String: Any],则可以执行以下操作:

if let dataDictionary = dataDictionary as? [String: Any] {
    // dataDictionary["access_token"] as AnyObject
}

答案 1 :(得分:0)

JSONSerialization.jsonObject会抛出错误,所以请在do catch

中捕获它
    do {
        let dataDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]
        let accessToken = dataDictionary["access_token"] as! AnyObject
    } catch let error as NSError {
        print(error)
    }