I have a query set up in Swift, that retrieves some values from a particular column. I'm trying to return the amount of objects that are in accordance with the query, and then sum up the rating numbers of the customer's rating column, to later divide them with the amount of orders, in order to get an average. I found on *, that I could do this by storing the different rating values in an array, but for some reason, only one value is stored in the array, so I keep getting an error. Here's the code:
我在Swift中设置了一个查询,它从特定列中检索一些值。我正在尝试返回符合查询的对象数量,然后总结客户评级列的评级数,以便稍后将它们除以订单数量,以获得平均值。我在*上发现,我可以通过在数组中存储不同的评级值来实现这一点,但由于某种原因,数组中只存储了一个值,所以我不断收到错误。这是代码:
var ordersArray: [Int]!
let query = PFQuery(className: "Orders")
query.whereKey("customer", equalTo: customerLet)
query.findObjectsInBackgroundWithBlock({(objects, error) -> Void in
if objects!.count == 0{
self.ratingLabel.text = ("5.0")
}else{
if let objects = objects{
for object in objects{
let ordersAmount = objects!.count
self.ordersArray.append((Int(object.objectForKey("rating") as! String))!
let totalOrders = self.ordersArray.reduce(0, combine: +)
let ratingAverage = (totalOrders / ordersAmount)
}
}
}
})
1 个解决方案
#1
1
Also the issue is that your array is not being initialized correctly. It should be like that :
此问题还在于您的阵列未正确初始化。它应该是这样的:
var ordersArray: [Int] = []()
Try this.
尝试这个。
for object in objects{
self.ordersArray.append((Int(object.objectForKey("rating") as! String))!
}
let ordersAmount = objects!.count
let totalOrders = self.ordersArray.reduce(0, combine: +)
let ratingAverage = (totalOrders / ordersAmount)
#1
1
Also the issue is that your array is not being initialized correctly. It should be like that :
此问题还在于您的阵列未正确初始化。它应该是这样的:
var ordersArray: [Int] = []()
Try this.
尝试这个。
for object in objects{
self.ordersArray.append((Int(object.objectForKey("rating") as! String))!
}
let ordersAmount = objects!.count
let totalOrders = self.ordersArray.reduce(0, combine: +)
let ratingAverage = (totalOrders / ordersAmount)