我有两个数组。
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"]
在这里,我想使用这些产品数量来计算每个价格。
答案 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)
假设您的输入数据以字符串数组的形式提供。
let quntityArr = ["1","3","4","7"]
let priceArr = ["£129.95", "£179.95","£169.95","£199.85"]
let quantities = quntityArr
.compactMap(Int.init)
let prices = priceArr
.map { $0.dropFirst() }
.compactMap (Double.init)
assert(quntityArr.count == quantities.count)
assert(priceArr.count == prices.count)
let results = zip(quantities, prices).map { Double($0) * $1 }.map { "£\($0)"}
["£129.95", "£539.8499999999999", "£679.8", "£1398.95"]