2016-09-15 131 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