我是 IOS 新手,所以这个问题可能是针对新手的。我确切地知道我想做什么,但问题是如何去做。我有字典的 JSON 数据,例如
{
"restaurants": [
{
"id": 1,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 3,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 4,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 5,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 6,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
}
]
}
我正在尝试使用此代码访问字典中的数组
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(URL_GET_DATA).responseJSON { response in
if let json = response.result.value {
let RestaurantArray : NSArray = json as! NSArray
for i in 0..<RestaurantArray.count{
self.restaurant.append(Restaurant(
restaurantPicture: (RestaurantArray[i] as AnyObject).value(forKey: "restaurantPicture") as? String,
restaurantName: (RestaurantArray[i] as AnyObject).value(forKey: "restaurantName") as? String,
status: (RestaurantArray[i] as AnyObject).value(forKey: "status") as? String
))
}
self.tableViewRestaurants.reloadData()
}
}
self.tableViewRestaurants.reloadData()
}
我收到此错误
Could not cast value of type '__NSSingleEntryDictionaryI' (0x1032e6e98) to 'NSArray' (0x1032e7f28).
2018-04-16 11:58:29.020876+0000 restaurant[6262:210307] Could not cast value of type '__NSSingleEntryDictionaryI' (0x1032e6e98) to 'NSArray' (0x1032e7f28).
我知道我想通过访问字典中的数组来做什么,但问题是如何去做。欢迎所有帮助和批评,因为我已经准备好学习。或者有没有一种方法可以尝试仅从数据库中获取数组,而不在餐馆字典中获取数组。谢谢大家
最佳答案
//As per above response
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(URL_GET_DATA).responseJSON { response in
if let json = response.result.value as! NSDictionary {
let restaurantsArray = json["restaurants"] as! NSArray
for dict in restaurantsArray {
let ID = (dict as! NSDictionary).value(forKey: "id") as? Int
//You can get more data like above
}
self.tableViewRestaurants.reloadData()
}
}
}
关于swift - 访问字典中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49857545/