-2

I had two Arrays.

let quntityArr = ["1","3","4","7"]

let priceArr = ["£129.95", "£179.95","£169.95","£199.85"]

I want to multiply these both Arrays in the following way

let totalArr = ["1*£129.95", "3*£179.95", "4*£169.95", "7*£199.85"]

Here I want to calculate each price with those product quantities.

vahdet
  • 6,357
  • 9
  • 51
  • 106
  • [This question](https://stackoverflow.com/questions/59527032/how-to-multiple-two-string-arrays-and-get-total-value-in-ios-swift-4) is almost identical, duplicate accounts? – Joakim Danielson Dec 30 '19 at 11:09

2 Answers2

2

You need

let quntityArr:[Double] = [1,3,4,7]

let priceArr = [129.95, 179.95,169.95,199.85]

let totalArr = zip(quntityArr, priceArr).map { "£\($0 * $1)" }

print(totalArr)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
2

Assuming your input data is provided as array of String.

1. Input Data

let quntityArr = ["1","3","4","7"]
let priceArr = ["£129.95", "£179.95","£169.95","£199.85"]

2. Convert input data in array of Int and Double

let quantities = quntityArr
    .compactMap(Int.init)
let prices = priceArr
    .map { $0.dropFirst() }
    .compactMap (Double.init)

3. Verify no input value has been discarded

assert(quntityArr.count == quantities.count)
assert(priceArr.count == prices.count)

4. Do the math

let results = zip(quantities, prices).map { Double($0) * $1 }.map { "£\($0)"}

5. Result

["£129.95", "£539.8499999999999", "£679.8", "£1398.95"]
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148