美文网首页从0到1学习iOSselector
iOS OC实现map、filter、reduce等高阶函数

iOS OC实现map、filter、reduce等高阶函数

作者: 一粒咸瓜子 | 来源:发表于2020-09-22 19:42 被阅读0次

    在 Swift 中,map filter reduce 等高阶函数的存在可以让我们更快的处理数据。
    在OC中实现对应方法:

    • map:处理数组中的每个元素,并返回一个新的结果数组。
    - (NSArray *)_map:(id(^)(id))hanlde {
        if (!hanlde || !self) return self;
        
        NSMutableArray *arr = NSMutableArray.array;
        for (id obj in self) {
            id new = hanlde(obj);
            [arr addObject:new];
        }
        return arr.copy;
    }
    
    
    /** Usages: */
    NSArray *languages = @[@"objctive-c", @"java", @"swift",@"javascript", @"php"];
    languages = [languages _map:^id _Nonnull(NSString *obj) {
      return [obj stringByAppendingString:@" !!"];
    }];
    
    NSLog(@"%@", languages);
    /** Prints
    (
        "objctive-c !!",
        "java !!",
        "swift !!",
        "javascript !!",
        "php !!"
    )
    */
    

    • filter:按照规则返回过滤之后的数组
    - (NSArray *)_filter:(BOOL(^)(id))handle {
        if (!handle || !self) return self;
        
        NSMutableArray *arr = NSMutableArray.array;
        for (id obj in self) {
            if (handle(obj)) {
                [arr addObject:obj];
            }
        }
        return arr.copy;
    }
    
    
    /** Usages: */
    NSArray *numbers = @[@1,@2,@5,@11,@6,@0,@3];
    NSArray *oddArr = [numbers _filter:^BOOL(NSNumber *obj) {
      return (obj.intValue %2 != 0);
    }];
        
    NSLog(@"%@", oddArr);
    /** Prints
    (
        1,
        5,
        11,
        3
    )
    */
    

    • reduce:按照规则将组内元素一一合并,返回最终结果
    - (id)_reduce:(id(^)(id, id))handle initial:(id)initial {
        if (!handle || !self || !initial) return self;
        if (self.count <1) return initial;
        
        id value = initial;
        for (id obj in self) {
            value = handle(value, obj);
        }
        return value;
    }
    
    
    /** Usages: */
    NSArray *numbers = @[@3,@2,@10];
    id result = [numbers _reduce:^id _Nonnull(NSNumber *obj1, NSNumber *obj2) {
      return @(obj1.intValue * obj2.intValue);
    } initial:@1];
        
    NSLog(@"%@", result);
    // Prints  "60"
    
    NSArray *words = @[@"hello", @"world", @"good", @"night"];
    id result = [words _reduce:^id _Nonnull(NSString *obj1, NSString *obj2) {
      return [NSString stringWithFormat:@"%@%@", obj1, obj2];
    } initial:@""];
        
    NSLog(@"%@", result);
    // Prints "helloworldgoodnight"
    

    • foreach:对每个元素做操作
    - (void)_forEach:(void(^)(id))handle {
        if (!handle || !self) return;
        
        for (id obj in self) {
            handle(obj);
        }
    }
    
    
    /** Usages: */
    [subviews _forEach:^(UIView *view) {
      [view removeFromSuperview];
    }];
    

    可改进:函数式调用
    难点:获取 block 签名函数

    相关文章

      网友评论

        本文标题:iOS OC实现map、filter、reduce等高阶函数

        本文链接:https://www.haomeiwen.com/subject/psqgyktx.html