Search code examples
iosswiftuitableviewindexpath

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


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

Solution

  • 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, +)