Tejas Pashte Tejas Pashte - 11 months ago 72
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)]


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
in table view
in table view
in table view
in table view
in table view
in table view

Answer Source

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) {

    orders = Orders.readOrdersFromArchive()

    if let orders = orders {

       for order in orders  {

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