输入“任何"从服务器中提取数据数组期间,Swift 3中没有下标成员 [英] Type "Any" has no subscript members in Swift 3 during pulling array of data from server

查看:84
本文介绍了输入“任何"从服务器中提取数据数组期间,Swift 3中没有下标成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将项目更新为swift 3.0,所有有关从服务器提取数据的代码在下面的图片中都给了我这个错误.

I'm trying to update my project to swift 3.0 and all codes about pulling data from server is give me this error in the following picture.

我尝试了很多可用的解决方案,但是没有用到有用的结果,在这种情况下是什么问题?

I tried a lot of solutions that is available here but with no useful result what is the problem in this case ?

 do {
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)


        if let countries = json["Countries"] as? [String: AnyObject] {
            for country in countries {
                if let couname = country["countryname"] as? [AnyObject] {
                    country_names.append(couname)
                }

                if let coucode = country["code"] as? [AnyObject] {
                    country_codes.append(coucode)
                }

            }
        }
    } catch {
        print("Error Serializing JSON: \(error)")
    }

推荐答案

在使用前将json强制转换为[String: Any].

Try casting json to [String: Any] before using it.

在这里您似乎也有一个错误:if let couname = country["countryname"] as? [AnyObject]

Also you seem to have an error here: if let couname = country["countryname"] as? [AnyObject]

您应该将其转换为[String: AnyObject]的数组:[[String: AnyObject]]

You should cast it to an array of [String: AnyObject]: [[String: AnyObject]]

调整后的代码如下:

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

    if let countries = json["Countries"] as? [[String: AnyObject]] {
        for country in countries {
            if let couname = country["countryname"] as? [AnyObject] {
                country_names.append(couname)
            }

            if let coucode = country["code"] as? [AnyObject] {
                country_codes.append(coucode)
            }

        }
    }
} catch {
    print("Error Serializing JSON: \(error)")
}

这篇关于输入“任何"从服务器中提取数据数组期间,Swift 3中没有下标成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆