我正在尝试使用来自REST服务的元素创建一个TableView,它是一个包含描述,标题,类别和图像的优惠券列表。所以我首先反序列化数据,把它放在一个数组中,然后将它转换成每个部分的特定数组,但是我的循环不起作用,有人可以帮我吗?
这是我的代码:
var couponsTitle : [String] = []
var couponsDesc : [String] = []
var couponsCat : [String] = []
func getCoupons(){
let miURL = URL(string: RequestConstants.requestUrlBase)
let request = NSMutableURLRequest(url: miURL!)
request.httpMethod = "GET"
if let data = try? Data(contentsOf: miURL! as URL) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
let parseJSON = json
let object = parseJSON?["object"] as! NSDictionary
let mainCoupon = object["mainCoupon"] as! NSArray
let coupons = object["coupons"] as! NSArray
for i in mainCoupon {
self.couponsCat.append((mainCoupon[i as! Int] as AnyObject).value(forKey: "category"))
}
for i in coupons {
self.couponsCat.append((coupons[i as! Int] as AnyObject).value(forKey: "category"))
}
for i in mainCoupon {
self.couponsDesc.append((mainCoupon[i as! Int] as AnyObject).value(forKey: “description"))
}
for i in coupons {
self.couponsDesc.append((coupons[i as! Int] as AnyObject).value(forKey: “description"))
}
for i in mainCoupon {
self.couponsTitle.append((mainCoupon[i as! Int] as AnyObject).value(forKey: “name"))
}
for i in coupons {
self.couponsTitle.append((coupons[i as! Int] as AnyObject).value(forKey: “name"))
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomeTableViewCell
cell.couponTitle.text = couponsTitle[indexPath.row]
cell.couponDescription.text = couponsDesc[indexPath.row].
cell.couponCategory.text = couponsCat[indexPath.row]
return cell
}
我最大的问题是我不知道如何在数组中加入循环但是每个部分的规范(我的意思是标题,描述,类别等)是否有任何想法?
答案 0 :(得分:1)
为什么没有为具有三个属性的优惠券定制类,而不是拥有三个数组(每个属性一个)?
class Coupon: AnyObject {
var description: String
var title: String
var category: String
init(description: String, title: String, category: String) {
self.description = description
self.title = title
self.category = category
}
}
如果你这样做,你可以通过做这样的事情来避免这么多的循环
for coupon in mainCoupon {
let description = mainCoupon["description"]
let title = mainCoupon["name"]
let category = mainCoupon["category"]
let newCoupon = Coupon(description: description, title: title, category: category)
couponsArray.append(newCoupon)
}