-1

I have Two arrays like below i a want calculate 2 array values and get total value according to qty. ["1", "1"] ["£129.95", "£129.95"]

SuryaTeja
  • 11
  • 1
  • 4
  • Can you show the code you have tried? You will need to iterate over the array indices, parse the strings to aNot Int and a decimal number and then perform the multiplication. – Paulw11 Dec 30 '19 at 07:36
  • For reference https://stackoverflow.com/questions/41884630/swift-convert-currency-string-to-double – Paulw11 Dec 30 '19 at 07:40
  • Since you have already asked a [similar question](https://stackoverflow.com/questions/59067075/how-to-multiple-euro-values-total-arrays-in-ios-swift-5-like-£179-95-£199-9) I assume you have some code you have tried and can share. – Joakim Danielson Dec 30 '19 at 08:06

1 Answers1

0

I'm not sure if you want to add/multiple numbers in both array. And not sure what do you want to calculate from two arrays. So I've added example code below to add and multiple two string arrays.

func calculateTwoArrays(){

        let array1 = ["1", "1"]
        let array2 = ["£129.95", "£129.95"]

        //Add all values together
        var total:Double = 0.0

        for value in array1 {

            if let number = Double(value.replacingOccurrences(of: "£", with: "")){

                total += number
            }
        }

        print("Total:\(total)")

        //Multiply array values, assuming array1 as quantity and array 2 as price.
        var priceArray = [Double]()

        for quantity in array1 {

            for price in array2 {

                if let quantityValue = Double(quantity), let priceValue = Double(price.replacingOccurrences(of: "£", with: "")){

                    priceArray.append(quantityValue*priceValue)
                }
            }
        }

        total = priceArray.reduce(0, +)

        print("Total:\(total)")
}
Natarajan
  • 3,241
  • 3
  • 17
  • 34
  • I want calculate array 1 index 0 to array 2 , array 1 index 1 to array 2 index 1 and final total like cart value – SuryaTeja Dec 30 '19 at 09:54
  • do you want to multiply and add like (array1-index-0 * array2-index-0and1) + (array1-index-1 with array2-index-0and1)? – Natarajan Dec 30 '19 at 10:45