【问题标题】:Is there a better way to flatten an NSArray of NSDictionaries?有没有更好的方法来展平 NSDictionaries 的 NSArray?
【发布时间】:2015-07-03 17:00:32
【问题描述】:

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

    @[@{@"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 编写转换?

【问题讨论】:

标签: ios objective-c swift nsarray nsdictionary


【解决方案1】:

一种方法是使用 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];

【讨论】:

  • 或者您可以使用 2 次 swift filter 调用来获取您的对象和总计,而不是使用 KVC,然后按照您的方式组合它们。
【解决方案2】:

到 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"];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多