Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/106.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 根据关键字添加分组字典元素的值_Ios_Arrays_Swift_Dictionary_Struct - Fatal编程技术网

Ios 根据关键字添加分组字典元素的值

Ios 根据关键字添加分组字典元素的值,ios,arrays,swift,dictionary,struct,Ios,Arrays,Swift,Dictionary,Struct,我有一系列的产品叫做“产品”。我已将数组分组,如下所示 let groupedBonds = Dictionary(grouping: data.offerings) { (Offering) -> String in return Offering.company } public struct Offering: Codable { public let company: String public let amount: In

我有一系列的产品叫做“产品”。我已将数组分组,如下所示

let groupedBonds = Dictionary(grouping: data.offerings) { (Offering) -> String in
            return Offering.company
        }

public struct Offering: Codable {
    public let company: String
    public let amount: Int
    public let location: String
}
字典的关键是
公司->[“ABCD”、“EFGH”、“IJKL”、“MNOP”]


我想把各公司的所有金额加起来。请帮助我实现此结果。

似乎您需要找到所有分组数组的总和,您可以使用
mapValues
实现此目的:

let amounts = groupedBonds.mapValues { $0.reduce(0) { $0 + $1.amount} }

amounts
将是一个字典,其键与
groupedBonds
(本例中为公司名称)相同,但其值为转换闭包的结果,转换闭包计算每个数组的和,不管是否一致。

似乎需要找到所有分组数组的和,您可以为此使用
mapValues

let amounts = groupedBonds.mapValues { $0.reduce(0) { $0 + $1.amount} }

金额
将是一个字典,其键与
groupedBonds
(本例中为公司名称)相同,但其值为转换闭包的结果,转换闭包计算每个数组的总和。

假设data.Offices等于

let offerings = [
    Offering(company: "A", amount: 7, location: "a"),
    Offering(company: "A", amount: 4, location: "a"),
    Offering(company: "B", amount: 2, location: "a"),
    Offering(company: "C", amount: 3, location: "a"),
]
我想把各公司的所有金额加起来

  let sumAmountByComany = offerings.reduce(into: [:]) { (result, offer)  in
         result[offer.company] = (result[offer.company] ?? 0 ) + offer.amount
    }
结果

[
 "C": 3,
 "B": 2,
 "A": 11
]

假设data.Offices等于

let offerings = [
    Offering(company: "A", amount: 7, location: "a"),
    Offering(company: "A", amount: 4, location: "a"),
    Offering(company: "B", amount: 2, location: "a"),
    Offering(company: "C", amount: 3, location: "a"),
]
我想把各公司的所有金额加起来

  let sumAmountByComany = offerings.reduce(into: [:]) { (result, offer)  in
         result[offer.company] = (result[offer.company] ?? 0 ) + offer.amount
    }
结果

[
 "C": 3,
 "B": 2,
 "A": 11
]

很高兴听到这个消息,如果答案对你有帮助,你可以接受/投票。很高兴听到这个消息,如果答案对你有帮助,你可以接受/投票。你也可以使用
reduce(into:)
,这样就不需要
var
你也可以使用
reduce(into:)
,这样就不需要
var