我正在尝试从每个tableView
单元格中获取总计,然后添加到总计标签中。由于每个单元格可能具有不同的数量和价格,因此我在数量和产品基本价格中都使用Array
s。
我已经遵循了这个问题/答案,但是看着这个问题的人正在使用以下结构:how to calculate the values in table view and to display in separate label
var total = 0.0
var basePriceArray = [2.45, 18.95, 3.8]
var quantityArray = [2.0, 1.0, 5.0]
cellForRowAt
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! BasketCell
let basePriceAtIndex = basePriceArray[indexPath.row]
let quantityAtIndex = quantityArray[indexPath.row]
let priceAtIndex = basePriceAtIndex * quantityAtIndex
//When I add the priceAtIndex to the cell label it is calculating perfectly
//ie 4.9, 18.95, 19
//Below is my problem
for _ in productNameArray {
total += priceAtIndex
}
print(total)
//The total is printing
14.700000000000001 (ignore the one)
71.55
128.55
弄清楚其背后的逻辑,它将priceAtIndex
乘以productNameArray
中有多少个产品(因为for-in
循环正在计算有多少个产品) 。然后将最后一个价格添加到下一个价格,即
4.9 x 3 = 14.7
18.95 x 3 = 56.85 + 14.7 = 71.55
19.00 x 3 = 57 + 56.85 + 14.7 = 128.55
我了解其背后的逻辑,但由于某种原因无法找出解决办法?
编辑1
忘记提及我的productNameArray
中有3种产品,因此x 3
答案 0 :(得分:1)
我同时使用数量和产品基本价格的数组
不要这样做。使用包含数量和价格的结构以及产品的计算属性
struct Product {
let name : String
// many other properties
var quantity : Int
var price : Double
var priceTotal : Double {
return Double(quantity) * price
}
}
和数据源数组
var products = [Product]()
在cellForRow map
乘积中将priceTotal
乘积并加起来
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! BasketCell
let total = products.map{$0.priceTotal}.reduce(0.0, +)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 2
cell.textLabel?.text = numberFormatter.string(from: NSNumber(value: total))
当然,如果Product
或quantity
发生变化,则必须更新数据源的price
实例。