有没有更好的方法来展平 NSDictionaries 的 NSArray?

Is there a better way to flatten an NSArray of NSDictionaries?

我有一组字典,看起来像这样:

    @[@{@"object" : @"circle", @"total" : @12},
      @{@"object" : @"square", @"total" : @7},
      @{@"object" : @"triangle", @"total" : @4},
    ];

我想把它扁平化成一个字典,其中键是对象,值是总数:

    @{@"circle" : @12,
      @"square" : @7,
      @"triangle" : @4,
    };

除了遍历数组和映射键之外,还有什么方法可以做到这一点吗?

NSMutableDictionary *objects = [[NSMutableDictionary alloc] init];
for (NSDictionary *object in array)
{
    [objects setObject:object[@"total"] forKey:object[@"object"];
}

如果没别的办法用Objective C,怎么转换成Swift?

一种方法是使用 KVC:

NSArray* array = @[@{@"object" : @"circle", @"total" : @12},
    @{@"object" : @"square", @"total" : @7},
    @{@"object" : @"triangle", @"total" : @4},
];
NSArray* objects = [array valueForKeyPath:@"object"];
NSArray* totals = [array valueForKeyPath:@"total"];
NSDictionary* final = [[NSDictionary alloc] initWithObjects:totals forKeys:objects];

到swift的转换如下:

var array = [[String : String]](); // Let this be your array
var requiredDictionary = [String : String](); //be your required dictionary
for object in array {
    let key = object["object"]
    requiredDictionary[key!] = object["total"];
}