从字典数组中读取int(NSCFNumber)

时间:2016-09-15 17:34:11

标签: ios arrays swift dictionary alamofire

我正在使用Alamofire和SwiftyJSON。我可以成功地从API中读取,如下所示:

var app = angular.module("MyApp", []);

app.controller("MainController", ['$scope', function ($scope) {
$scope.info = function () {


    $scope.fName = fName;
    $scope.email = '';
    $scope.phone = '';
    $scope.lName = '';
    $scope.birth = '';
    $scope.food = '';
    $scope.about = '';

}


}])

但我无法从字典中获取值 dict [“id”] dict [“userId”] 以显示在单元格中。

Alamofire.request(.GET, "https://jsonplaceholder.typicode.com/posts").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)

if let resData = swiftyJsonVar.arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.results_tableView.reloadData()
}
} }

enter image description here

这是我的词典数组在顶部的声明:

var dict = arrRes[indexPath.row]
cell.label_body.text = dict["body"] as? String
cell.label_title.text = dict["title"] as? String
cell.label_id.text = dict["id"] as? String **//prints (nil)**
cell.label_userId.text = dict["userId"] as? String **//prints (nil)**

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您可以尝试这样

if let userId = dict["userId"] {
   cell.label_userId.text = "\(userId)"
}

希望这能解决你的问题

答案 1 :(得分:1)

这是示例字典,我们从server获取。这里的id是id,userid是整数。因此,不是类型转换为字符串,而是输入强制转换为Int或NSNumber。

{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"

}

cell.label_id.text = String(dict["id"] as? Int ?? 0)
cell.label_userId.text = Stringdict["userId"] as? Int ?? 0)

OR

cell.label_id.text = String(dict["id"] as? NSNumber ?? 0)
cell.label_userId.text = String(dict["userId"] as? NSNumber ?? 0) 

答案 2 :(得分:0)

如果我理解你的json响应,你可以得到如下:

   if let id = dict["id"] {
      cell.label_id.text = "\(id)"
   }
   if let userID = dict["userId"] {
      cell.label_userId.text = "\(userID)"
   }