链式编程的特点
链式编程通过点语法连续调用函数,将一系列代码执行动作串联起来,让代码更加简洁, 可读性更强,不用单独一个一个的执行。
Objective-C和Swift代码写法上有些差别
Objective-C
对象方法的返回值是一个Block,在返回Block函数中做相应的逻辑处理并返回当前对象Swift
对象方法的返回值是当前对象,需要操作的值以形参传入
OC版
CaculateMake 具体方法类
####CaculateMake.h
#import <UIKit/UIKit.h>
@interface CaculateMake : NSObject
/** 结果 */
@property (nonatomic, assign) CGFloat result;
- (CaculateMake *(^)(CGFloat))add;
- (CaculateMake *(^)(CGFloat))sub;
@end
####CaculateMake.m
#import "CaculateMake.h"
@implementation CaculateMake
- (CaculateMake *(^)(CGFloat))add {
return ^CaculateMake *(CGFloat value) {
self.result += value;
return self;
};
}
- (CaculateMake *(^)(CGFloat))sub {
return ^CaculateMake *(CGFloat value) {
self.result -= value;
return self;
};
}
@end
点语法调用类
#import <UIKit/UIKit.h>
#import "CaculateMake.h"
@interface Caculate : NSObject
+ (CGFloat)caculate:(void(^)(CaculateMake *make))caculateBlock;
@end
#import "Caculate.h"
@implementation Caculate
+ (CGFloat)caculate:(void (^)(CaculateMake *))caculateBlock {
CaculateMake *make = [[CaculateMake alloc] init];
caculateBlock(make);
return make.result;
}
@end
Swift版
class CaculateMake {
var result: Int = 0
func add(num: Int) -> CaculateMake {
result += num
return self
}
func sub(num: Int) -> CaculateMake {
result -= num
return self
}
}
class Caculate {
static func beginCaculate(caculateBlock: (CaculateMake) -> ()) -> Int {
let caculateMake = CaculateMake()
caculateBlock(caculateMake)
return caculateMake.result
}
}
#### 使用
let n = Caculate.beginCaculate { (make) in
make.add(num: 10).add(num: 20)
}