gpt4 book ai didi

arrays - 我应该如何使用 swift 字典数组来获取所有值?

转载 作者:行者123 更新时间:2023-11-28 09:48:53 25 4
gpt4 key购买 nike

我的字典是这样的:

["Coke": ["1", "80"], "Appetizer": ["3", "70"], "Water": ["4", "70"],

"Noodle": ["2", "40"], "Pizza": ["7", "80"], "Steak": ["7", "60"]]

value是一个数组,包含两个值

第一个数字就像你订购了多少商品

第二个数字就像小计

我只是想知道如何获取第二个数字并将其保存到新变量中?

因为我需要将所有数字相加才能代表总价

最佳答案

let dict = ["Coke": ["1", "80"], "Appetizer": ["3", "70"], "Water": ["4", "70"], "Noodle": ["2", "40"], "Pizza": ["7", "80"],  "Steak": ["7", "60"]]

简答(直接针对您的问题)

var price = dict.values.reduce(0, { $0 + Double($1[0])! * Double($1[1])! }) // If you need only the price, remove the multiplier
print(price) //1630.0

长答案

就像 SO 上总是建议的那样,您应该创建一个数据模型来保存您的信息。在这种情况下,它看起来像这样,

struct Bill {
var item: String
var amount: Int
var price: Double
}

// For the sake of the example i'll convert your dictionary into Price
var billArray: [Bill] = []
for (key, value) in dict {
billArray.append(Bill(item: key, amount: Int(value[0]) ?? 0, price: Double(value[1]) ?? 0))
}

// The actual solution that you apply to the price array
var totalBill = billArray.reduce(0, { $0 + Double($1.amount) * $1.price}) // If you need only the price, remove the multipler amount
print(totalBill) //1630.0

关于arrays - 我应该如何使用 swift 字典数组来获取所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53515394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com