(SWIFT 4) How to calculate sum of the columns indexpath.row in the tableview?

1k Views Asked by At

how to calculate the sum of the same columns in different cells, not the sum in the same cell.

I don't know how to solve it.

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
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

If you want to enumerate over elements the way you try to do:

var sum = 0
for pair in listPrice.enumerated() {
    sum += Int(pair.element) //listPrice[pair.index]
}

Or just use this:

let sum = ad2?.listPrice.compactMap(Int.init).reduce(0, +)
0
On

Use compactMap to map the String array to Int and reduce to sum up the items.

let ad2 = UIApplication.shared.delegate as! AppDelegate

...

let sum = ad2.listPrice.compactMap(Int.init).reduce(0, +)

and cellForRow is the wrong place for the code.

Notes :

  • Basically don't use multiple arrays as data source.
  • If listPrice contains numeric values anyway use a more appropriate type like Int or Double.
  • Don't use AppDelegate as a common place to store data.
  • If AppDelegate doesn't exist the app won't even launch so it's perfectly safe to force cast it.