Arrays 如何组合字典中的重复键并在swift中汇总值?
就像我有一个2个客户名称,具有相同的键,但值不同。我想把它们的值加起来,在输出中只做一个键,但有一个总值。Arrays 如何组合字典中的重复键并在swift中汇总值?,arrays,swift,dictionary,filter,swift3,Arrays,Swift,Dictionary,Filter,Swift3,就像我有一个2个客户名称,具有相同的键,但值不同。我想把它们的值加起来,在输出中只做一个键,但有一个总值。 在我的tableview中,单元格显示为重复的,而不是值的总和,并且customername(键)也重复。请帮忙。。我尝试了所有方法,但都未能更正输出。您可以使用Dictionary.init(ukeysandvalues:S,uniquingKeysWith combine:(Value,Value)throws->Value),它接受元组的序列,存储键值对和闭包,定义如何处理重复的键值
在我的tableview中,单元格显示为重复的,而不是值的总和,并且customername(键)也重复。请帮忙。。我尝试了所有方法,但都未能更正输出。您可以使用
Dictionary.init(ukeysandvalues:S,uniquingKeysWith combine:(Value,Value)throws->Value)
,它接受元组的序列,存储键值对和闭包,定义如何处理重复的键值
var dictionary: [String : Any] = [:]
for revenueItem in revenues {
if let currentValue = dictionary[revenueItem.customerName] {
dictionary[revenueItem.customerName] = [currentValue] + [revenueItem.revenue]
print("hellooooooooooo \(currentValue)")
} else {
dictionary[revenueItem.customerName] = [revenueItem.revenue]
}
}
测试代码:
// Create the key-value pairs
let keysAndValues = revenues.map { ($0.customerName, $0.revenue) }
// Create the dictionary, by adding the values for matching keys
let revenueDict = Dictionary(keysAndValues, uniquingKeysWith: { $0 + $1 })
您可以使用Dictionary.init(keysAndValues:S,uniquingKeysWith combine:(Value,Value)throws->Value)
,它接受元组的序列,存储键值对和闭包,闭包定义如何处理重复的键
var dictionary: [String : Any] = [:]
for revenueItem in revenues {
if let currentValue = dictionary[revenueItem.customerName] {
dictionary[revenueItem.customerName] = [currentValue] + [revenueItem.revenue]
print("hellooooooooooo \(currentValue)")
} else {
dictionary[revenueItem.customerName] = [revenueItem.revenue]
}
}
测试代码:
// Create the key-value pairs
let keysAndValues = revenues.map { ($0.customerName, $0.revenue) }
// Create the dictionary, by adding the values for matching keys
let revenueDict = Dictionary(keysAndValues, uniquingKeysWith: { $0 + $1 })
为什么要使用[String:Any]
?显示您的表视图代码。这可能需要更改,因为您似乎使用了错误的类型。为什么要使用[String:Any]
?显示您的表视图代码。这可能需要更改,因为您似乎使用了错误的类型。如何使其成为for循环?我的数据来自数据库。这些是字典。如何使其成为肯德基的总价值,并使其成为一个一键输出。?“customerName”:“KFC”“revenue”:12345.2“salesType”:“revenue”“customerName”:“KFC”“revenue”:12345.2“salesType”:“revenue”“customerName”:“Andoks”“revenue”:54321.4“salesType”:“revenue”@miniosdwarf不需要for循环。我的代码已经完全符合您的要求。如果你尝试一下,你就会明白。如何使它成为for循环?我的数据来自数据库。这些是字典。如何使其成为肯德基的总价值,并使其成为一个一键输出。?“customerName”:“KFC”“revenue”:12345.2“salesType”:“revenue”“customerName”:“KFC”“revenue”:12345.2“salesType”:“revenue”“customerName”:“Andoks”“revenue”:54321.4“salesType”:“revenue”@miniosdwarf不需要for循环。我的代码已经完全符合您的要求。如果你试一试,你就会明白。