链式编程与函数编程

1. 链式编程

要实现的效果: make.left.equalTo(superview.mas_left)

分析只有 block 可以用()调用方法. 所以 make.应该返回 block
void(^block)() = ^{
    //code...
};
block();

例如:
self.test();
- (void(^)())test{
    voie(^block)() = ^{
          //code...
     };
}

2. 函数式编程

mgr.add(5).add(6).add(7);
mgr.add 返回一个 block
block返回 mgr 就可继续调用 block 了.

例子:

#import 

@interface CaculatorManager : NSObject

@property (nonatomic, assign)NSInteger result;


- (CaculatorManager *)caculator : (NSInteger(^)(NSInteger result))block;

- (void)log;

@end
#import "CaculatorManager.h"

@implementation CaculatorManager

- (CaculatorManager *)caculator:(NSInteger (^)(NSInteger))block{
    _result = block(_result);
    NSLog(@"%ld", _result);
    return  self;
}

- (void)log{
    NSLog(@"%ld", _result);
}

@end
#import "ViewController.h"
#import "CaculatorManager.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
 
    CaculatorManager *mgr = [[CaculatorManager alloc] init];
    [[mgr caculator:^NSInteger(NSInteger result) {
        
        result += 5;
        return result;
        
    }] log];
    
}

@end

你可能感兴趣的:(链式编程与函数编程)