如何在Swift中将数组的每个元素与下一个数组的每个元素相乘?

时间:2019-12-30 10:32:56

标签: arrays swift multiplication

我有两个数组。

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

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

我想通过以下方式将这两个数组相乘

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

在这里,我想使用这些产品数量来计算每个价格。

2 个答案:

答案 0 :(得分:2)

您需要

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)

答案 1 :(得分:2)

  

假设您的输入数据以字符串数组的形式提供。

1。输入数据

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

2。将输入数据转换为Int和Double数组

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

3。确认没有输入值被丢弃

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

4。做数学

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

5。结果

["£129.95", "£539.8499999999999", "£679.8", "£1398.95"]