![](/img/trans.png)
[英]Calculating sum until the indexPath.row instead of total using tableView
[英](SWIFT 4) How to calculate sum of the columns indexpath.row in the tableview?
如何計算不同單元格中相同列的總和,而不是同一單元格中的總和。
我不知道如何解決。
import UIKit
class ResultViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
@IBOutlet var tableview: UITableView!
@IBAction func backPage(_ sender: Any) {
self.presentingViewController?.dismiss(animated: true)
}
let ad2 = UIApplication.shared.delegate as? AppDelegate
@IBAction func resetHist(_ sender: Any) {
ad2?.listPrice = [String]()
ad2?.listAmt = [String]()
tableview.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ad2?.listPrice.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
cell.resultPrice?.text = ad2?.listPrice[indexPath.row]
cell.resultAmt?.text = ad2?.listAmt[indexPath.row]
var sum = 0
// how to calculate sum of the same columns in different cells
for i in ad2?.listPrice.count {
sum += Int(ad2?.listPrice[i])
}
return cell
}
}
使用compactMap
將String
數組映射到Int
並使用reduce
來總結項目。
let ad2 = UIApplication.shared.delegate as! AppDelegate
...
let sum = ad2.listPrice.compactMap(Int.init).reduce(0, +)
cellForRow
是代碼的錯誤位置。
注意事項:
listPrice
無論如何listPrice
包含數值,請使用更合適的類型,如Int
或Double
。AppDelegate
用作存儲數據的常用位置。AppDelegate
不存在,該應用程序甚至不會啟動,因此強制轉換它是完全安全的。如果您想按照您嘗試的方式枚舉元素:
var sum = 0
for pair in listPrice.enumerated() {
sum += Int(pair.element) //listPrice[pair.index]
}
或者只是使用這個:
let sum = ad2?.listPrice.compactMap(Int.init).reduce(0, +)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.