计算字符串数组中的价格 Array<String>
Calculate of prices in within an array of strings Array<String>
我有一个描述汽车零件列表的数组(Swift/IOS,数组已经在这样的结构中,来自其他来源。):
let parts = [
"Wheel = 230$",
"Door = 200$",
"Wheel = 300$",
"Seat = 150$",
"Seat = 150$",
"Rugs = 100$"]
我需要计算每种零件的汽车零件价格总和。这是我正在寻找的结果:
let expectedResult = [
"wheel 530$",
"Door 200$",
"Seat 300$",
"Rugs 100$"
]
我不明白怎么做。
这是一个解决方案,我循环遍历数组并将每个元素拆分为“=”,然后使用字典将这些值相加。完成后,字典将转换回数组
let parts = [
"Wheel = 230$",
"Door = 200$",
"Wheel = 300$",
"Seat = 150$",
"Seat = 150$",
"Rugs = 100$"]
var values = [String: Int]() // Used to calculate totals per part
parts.forEach { string in
let split = string.split(separator: "=")
// Make sure the split worked as expected and that we have an integer value after the =
guard split.count == 2,
let value = Int(String(split[1]).trimmingCharacters(in: .whitespaces).dropLast()) else { return }
let key = String(split[0]).trimmingCharacters(in: .whitespaces)
// Sum values over the part name
values[key, default: 0] += value
}
// Convert back to an array of strings
let output = values.map { "\([=10=].key) \([=10=].value)$"}
print(output)
我有一个描述汽车零件列表的数组(Swift/IOS,数组已经在这样的结构中,来自其他来源。):
let parts = [
"Wheel = 230$",
"Door = 200$",
"Wheel = 300$",
"Seat = 150$",
"Seat = 150$",
"Rugs = 100$"]
我需要计算每种零件的汽车零件价格总和。这是我正在寻找的结果:
let expectedResult = [
"wheel 530$",
"Door 200$",
"Seat 300$",
"Rugs 100$"
]
我不明白怎么做。
这是一个解决方案,我循环遍历数组并将每个元素拆分为“=”,然后使用字典将这些值相加。完成后,字典将转换回数组
let parts = [
"Wheel = 230$",
"Door = 200$",
"Wheel = 300$",
"Seat = 150$",
"Seat = 150$",
"Rugs = 100$"]
var values = [String: Int]() // Used to calculate totals per part
parts.forEach { string in
let split = string.split(separator: "=")
// Make sure the split worked as expected and that we have an integer value after the =
guard split.count == 2,
let value = Int(String(split[1]).trimmingCharacters(in: .whitespaces).dropLast()) else { return }
let key = String(split[0]).trimmingCharacters(in: .whitespaces)
// Sum values over the part name
values[key, default: 0] += value
}
// Convert back to an array of strings
let output = values.map { "\([=10=].key) \([=10=].value)$"}
print(output)