2016-09-15 137 views
0

我正在使用Alamofire和SwiftyJSON。我可以成功地读取API如下:从字典数组中读取int(NSCFNumber)

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() 
} 
} } 

但我不能获取值字典[“ID”]字典[“用户id”]从字典中的单元格中显示。

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)** 

enter image description here

这是我的字典的数组的顶部的信息声明:

var arrRes = [[String:AnyObject]]() //Array of dictionary 

非常感谢您的任何帮助。

回答

1

你可以尝试这样的

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

希望这将解决您的问题

1

这是样本字典,我们从server.Here得到的ID是一个ID和用户ID是integers.So而不是类型转换为字符串,类型转换为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) 
0

如果我正确地理解你的JSON响应,可以如下得到它:

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

非常感谢你“桑托斯”。你的回答是真实的,但是我接受他,就像我之前看到的那样。 – Umitk