7.2 C
Canberra
Thursday, October 23, 2025

ios – Calculating Buying Basket whole in swift


What’s one of the best ways to calculate whole of a buying basket when the situation is that ,

  1. you probably have similar merchandise twice then buyer will get 50% low cost.
  2. you probably have similar merchandise 3 occasions then buyer will get 1 merchandise free of charge , Mainly purchase 2 get 1 free.

As an example ,, giving the array of fruits ..

[
  Basket(productName: "Apple", productPrice: 1, productQuantity: 1),
  Basket(productName: "Banana", productPrice: 2, productQuantity: 3),
  Basket(productName: "Kiwi", productPrice: 3, productQuantity: 2),
]

Giving above buying basket …

Fruits Identify worth

Apple * 1 = 1

Banana * 3 = 6

Kiwi * 2 = 6

Grand whole. = 13 ..

the place the grand whole needs to be 8. I’ve seen some instance to return grand whole utilizing scale back operate the place I can return grand whole however I undecided How can I obtain it.

Code I’ve written but it surely return empty ..

struct Basket {
  var productName: String
  var productPrice: Int
  var productQuantity: Int
}
 
class ShoppingCart {
  
  var outcome: [Basket] = []
  var productTotal: Double = 0
  
  func calculateDiscountOfBasket(basket: [Basket]) -> Double {
    
    for x in basket {
      if let index = outcome.firstIndex(the place: { $0.productName == x.productName }) {
        outcome[index].productQuantity += 1
      } else {
        outcome.append(x)
      }
    }
    whole(basket: basket)
    return productTotal
  }
  
  func whole(basket: [Basket]) {
    
    for x in basket {
      if  x.productQuantity == 3 {
        productTotal = outcome.scale back(0.0, { whole, product in
          whole + Double((product.productQuantity * product.productPrice) - product.productPrice)
        })
      }
    }
  }
}

var productArray = [
  Basket(productName: "Apple", productPrice: 1, productQuantity: 1),
  Basket(productName: "Banana", productPrice: 2, productQuantity: 3),
  Basket(productName: "Kiwi", productPrice: 3, productQuantity: 2),
]

var  productClass = ShoppingCart()

let outcome = productClass.calculateDiscountOfBasket(basket: productArray)
print("Whole: (outcome)")

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles