为什么我得到的 Int64 值是 nil?

Why am I getting nil for the Int64 value?

我 运行 此代码并正确获取客户名称,但当涉及到整数(奖励数量、汽车数量、狗数量)时,似乎我没有从 API('??0' 部分开始并且 returns 为零)。

这是我的代码:

func getAllClients() {
    AF.request("xxxxxxxxxxxxx", headers: headers).responseJSON {response in
        let result = response.value
        var allCli: [ClientsData] = []
        if result != nil {
            let dataDictionary = result as! [Dictionary <String, AnyObject>]
            for clientsData in dataDictionary {
                let cllstname = clientsData["cllstname"] as? String ?? "Error"
                let noofawards = clientsData["noofawards"] as? Int64 ?? 0
                let noofcars = clientsData["noofcars"] as? Int64 ?? 0
                let noofdogs = clientsData["noofdogs"] as? Int64 ?? 0
                let clientsObject = ClientsData (cllstname: cllstname, noofawards: noofawards, noofcars: noofcars, noofdogs: noofdogs)

                allCli.append(clientsObject)
            }
        }
        self.allClients = allCli.sorted(by: { [=10=].noofawards > .noofawards })
    }
}

但是,如果我这样做

print(clientsData)

我在调试部分得到了很好且完整的响应。所有号码都在那里,所以 API 正在发送,我正在接收。

为什么我得到的结果为零,如何解决这个问题?

你应该看看原始的 JSON。例如,抓取 data

let string = response.data.flatMap { String(data: [=10=], encoding: .utf8) }
print(string ?? "Unable to get String representation of the data")

我打赌这些数字会被引号括起来,这意味着它们实际上是数值的字符串表示,而不是实际的数字:

[{"noofcars": "2", "cllstname": "Smith", ...

请注意,我要求您查看原始 JSON,而不仅仅是已经解码的 result。我们需要看看原始 JSON 是如何表示这些数值的。

让我们暂时假设我的假设是正确的,您将这些值作为字符串获取。显然,正确的解决方案是 Web 服务应将数值作为数字而不是字符串发送。但是您想要使用现有的 JSON,您首先要获得 numofcars(等)的 String 表示,然后将其转换为数值。例如:

AF.request("xxxxxxxxxxxxx", headers: headers).responseJSON { response in
    guard let dictionaries = response.value as? [[String: Any]] else { return }

    self.allClients = dictionaries.compactMap { dictionary -> ClientsData? in
        let cllstname = dictionary["cllstname"] as? String ?? "Error"
        let awards = (dictionary["noofawards"] as? String).flatMap { Int([=12=]) } ?? 0
        let cars = (dictionary["noofcars"] as? String).flatMap { Int([=12=]) } ?? 0
        let dogs = (dictionary["noofdogs"] as? String).flatMap { Int([=12=]) } ?? 0
        return ClientsData(cllstname: cllstname, noofawards: awards, noofcars: cars, noofdogs: dogs)
    }
    .sorted { [=12=].noofawards > .noofawards }
}

FWIW,请原谅上面的重构,因为我建议 mapcompactMap 而不是构建一个空数组并向其附加值。就是简洁了一点