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.

enter image description here

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)")
    }
Samah Ahmed
  • 419
  • 8
  • 24

2 Answers2

3

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

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

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

The adjusted code would look like:

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)")
}
d.felber
  • 5,288
  • 1
  • 21
  • 36
0

Use this instead of just a let json.

guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:AnyObject] else { return }
Callam
  • 11,409
  • 2
  • 34
  • 32
  • I tried this line but now the error appears in the following lines at the two if statements Type '(key: String, value: AnyObject)' has no subscript members – Samah Ahmed Oct 26 '16 at 09:58