swiftalamofirensdictionaryswifty-json

Parse Alamofire result swift


I'm very lost parsing the following response from an AF request – let json = result as! NSDictionary – in Swift:

{
    errors =     (
    );
    get = statistics;
    parameters =     {
        country = germany;
    };
    response =     (
                {
            cases =             {
                "1M_pop" = 14303;
                active = 317167;
                critical = 4179;
                new = "+15161";
                recovered = 863300;
                total = 1200006;
            };
            continent = Europe;
            country = Germany;
            day = "2020-12-08";
            deaths =             {
                "1M_pop" = 233;
                new = "+380";
                total = 19539;
            };
            population = 83900328;
            tests =             {
                "1M_pop" = 347331;
                total = 29141172;
            };
            time = "2020-12-08T09:15:08+00:00";
        }
    );
    results = 1;
}

Any idea how to get the actual case numbers, i.e. for example the number of new cases?

So far I have tried the following (error throwing) approach:

if let responseDict = result as? NSDictionary {
                            if let data = responseDict.value(forKey: "response") as?
                                [NSDictionary] {
                                
                                // Get case numbers
                                guard let cases = data[0]["cases"] else { return }
                                guard let casesPerOneMil = cases[0] as! Int else { return }
                                print(casesPerOneMil)
                            }
                        }

Solution

  • Basically don't use NS... collection types in Swift at all, use native types.
    And don't use value(forKey, use key subscription.

    And you have to conditional downcast Any to the expected concrete type.

    There is another mistake: The object for cases is a dictionary, note the {} and you have to get the value for casesPerOneMil with key subscription, too

    if let responseDict = result as? [String:Any], 
       let dataArray = responseDict["response"] as? [[String:Any]],
       let firstDataItem = dataArray.first {
            
            // Get case numbers
            guard let cases = firstDataItem["cases"] as? [String:Any] else { return }
            guard let casesPerOneMil = cases["1M_pop"] as? Int else { return }
            print(casesPerOneMil)
        }
    }