NSArray Equivalent of Map

后端 未结 11 1783
萌比男神i
萌比男神i 2020-11-28 05:06

Given an NSArray of NSDictionary objects (containing similar objects and keys) is it possible to write perform a map to an array of specified key?

11条回答
  •  Happy的楠姐
    2020-11-28 05:44

    To summarize all other answers:

    Ruby (as in the question):

    array.map{|o| o.name}
    

    Obj-C (with valueForKey):

    [array valueForKey:@"name"];
    

    Obj-C (with valueForKeyPath, see KVC Collection Operators):

    [array valueForKeyPath:@"[collect].name"];
    

    Obj-C (with enumerateObjectsUsingBlock):

    NSMutableArray *newArray = [NSMutableArray array];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
         [newArray addObject:[obj name]];
    }];
    

    Swift (with map, see closures)

    array.map { $0.name }
    

    And, there are a couple of libraries that allow you to handle arrays in a more functional way. CocoaPods is recommended to install other libraries.

提交回复
热议问题