输入' [String:Any]'在Swift中没有下标成员

时间:2017-07-15 06:51:10

标签: json swift networking struct

我正在尝试从json结果中获取信息并追加并访问某些键值。但是,我收到了错误" Type' [String:Any]'没有下标成员。

        let json = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
        for case let studentsInfo in json["results"] {
            if let studentInfo = StudentResults(json: result) {
                let name = firstName + " " + lastName
                StudentsResults.append(name)
            }

这也是我在扩展中放置的结构。

struct StudentResults{
    let firstName: String
    let lastName: String
    let latitude: Double
    let longitude: Double
    let mapString:String
    let mediaURL: String
    let objectID:String
    let uniqueKey: String
    let updatedAt: String
}

convenience init?(json: [String: Any]) {
    guard let firstName = json["firstName"] as? String,
          let lastName = json["lastName"] as? String
        else {
            return nil
    }
    return nil

如果您想看一下这个项目,这也是我的GitHub页面

https://github.com/SteveBurgos95/UdacityMapProject

1 个答案:

答案 0 :(得分:0)

在我看来问题在于这行代码:

let json = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]

虽然你强迫在as! [String: Any]投射,try?会给你一个可选值。

您有两种选择。您可以成为一个疯狂的人并将try?更改为try!,或者您可以采取更安全的方法并将代码包装起来:

do {
    guard let json = try JSONSerialization.jsonObject(with: data!, options: []) as [String: Any] else { return }
    …
} catch {
    // HANDLE ERROR
}