解析 Alamofire 结果 swift
Parse Alamofire result swift
我无法解析来自 AF
请求的以下响应 – let json = result as! NSDictionary
– 在 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;
}
知道如何获得实际病例数,例如 new
病例数吗?
到目前为止,我已经尝试了以下(错误抛出)方法:
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)
}
}
基本上不要在 Swift 中使用 NS...
集合类型,使用原生类型。
并且不要使用value(forKey
,使用密钥订阅。
并且您必须有条件地向下转换 Any
到预期的具体类型。
还有一个错误:cases
的对象是一个字典,注意 {}
并且你也必须通过密钥订阅来获取 casesPerOneMil
的值
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)
}
}
我无法解析来自 AF
请求的以下响应 – let json = result as! NSDictionary
– 在 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;
}
知道如何获得实际病例数,例如 new
病例数吗?
到目前为止,我已经尝试了以下(错误抛出)方法:
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)
}
}
基本上不要在 Swift 中使用 NS...
集合类型,使用原生类型。
并且不要使用value(forKey
,使用密钥订阅。
并且您必须有条件地向下转换 Any
到预期的具体类型。
还有一个错误:cases
的对象是一个字典,注意 {}
并且你也必须通过密钥订阅来获取 casesPerOneMil
的值
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)
}
}