不管是Block還是Closure在編碼過程中都極大的改善了代碼的結(jié)構(gòu),使其更為緊湊,其值捕獲的特性更是方便,下面記錄一下各類使用方法
Block
本地變量
returnType (^blockName)(parameterTypes) = ^returnType(parameterTypes){...};
屬性
@property (nonatomic, copy, nullablility) returnType (^blockName)(parameterTypes);
方法的參數(shù)
- (void)someMethod:(returnType (^nullability)(parameterTypes))blockName
調(diào)用方法的參數(shù)
[someObject someMethod:^returnType(parameterTypes){...}];
宏定義
// 定義
typedef returnType (^TypeName)(parameterTypes);
// 調(diào)用
TypeName blockName = ^returnType(parameterTypes) {...};
關(guān)于Block內(nèi)存管理,有出門左轉(zhuǎn),看樓主之前的這篇文章
Closure
變量
var closureName: (ParameterTypes) -> (ReturnType)
常量
let closureName: ClosureType = {...}
可選值
var closureName: ((ParameterTypes) -> (ReturnType))?
別名定義
typealias ClosuerType = (ParameterTypes) -> (ReturnType)
作為函數(shù)的調(diào)用參數(shù)
func({ (ParameterTypes) -> (ReturnType) in statements })
函數(shù)參數(shù)
array.sort({ (item1: Int, item2: Int) -> Bool in return item1 < item2 })
隱式類型函數(shù)參數(shù),這種寫法利用了swift的類型推斷特性
array.sort({ (item1, item2) -> Bool in return item1 < item2 })
省略返回值寫法
array.sort({ (item1, item2) in return item1 < item2 })
尾閉包寫法,當(dāng)閉包作為函數(shù)的最后一個(gè)參數(shù)的時(shí)候,可以使用尾閉包寫法
array.sort{ (item1, item2) in return item1 < item2 }
尾閉包簡寫
array.sort{ return $0 < $1}
array.sort{ $0 < $1 }
array.sort{ < } // swift中的符號(hào)其實(shí)是一個(gè)函數(shù)
當(dāng)有值捕獲的時(shí)候注意循環(huán)引用
array.sort( { [unowned self] (item1: Int, item2: Int) -> Bool in return item1 < item2 } )
優(yōu)化寫法
array.sort{ [unowned selft] in return item1 < item2 }
關(guān)于Closure內(nèi)存管理,有出門右轉(zhuǎn),看樓主之前的這篇文章