Block 闭包简查记录

像 Block 这种闭包,就是怎么用怎么爽,怎么用怎么喜欢的编码方式了。

闭包很伟大,也是各个语言都实现了的基础语法。我这边对闭包的理解,就是:内部函数持有外部变量

但是各个语言都有需要注意的点,如 iOS 里面的循环引用,Swift 里面的逃逸闭包,Python 里面的闭包变量延迟定义等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
As a local variable:
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

As a property:
@property (nonatomic, copy, nullability) returnType (^blockName)(parameterTypes);

As a method parameter:
- (void)someMethodThatTakesABlock:(returnType (^nullability)(parameterTypes))blockName;

As an argument to a method call:
[someObject someMethodThatTakesABlock:^returnType (parameters) {...}];

As a typedef:
typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};