Tejas Pashte Tejas Pashte - 1 month ago 20
iOS Question

Trying to calculate the the price of product in Swift3 Tableview controller

I am trying to calculate the total of product price all the products. So, I am able to get the total but it is generating array of ouput. But I only need a final total.

This is my git repo:[(github.com/sulkytejas/shopping-cart)]

code:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cartCell", for: indexPath)
let order = orders?[indexPath.row]
let prices = [order?.product?.price]
print("in table view")
for price in prices {
total += Double(price!)
}
print (total)
cell.textLabel?.text = order?.product?.name
return cell
}


Output :

in table view
1810636.0
in table view
1810676.0
in table view
1810766.0
in table view
1810806.0
in table view
1810821.0
in table view
1810911.0
in table view
1810951.0

Answer

You need to change readOrdersFromArchive function in orders.swift file. If you don't have order history, this function always returns nil value. That is why you can not append any order in the orders array in your addToCartPressed function.

class func readOrdersFromArchive() -> [Order]? 
{
    return NSKeyedUnarchiver.unarchiveObject(withFile: archiveFilePath()) as? [Order] ?? [Order]()
}

I was able to see the total value after adding the code below.

var total = 0.0


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    orders = Orders.readOrdersFromArchive()

    if let orders = orders {

       for order in orders  {

          total += (order.product?.price!)!

          }
       }

       print(total)

 }
Comments