《Using Swift with Cocoa and Obje
2016-04-13 本文已影响34人
公爵海恩庭斯
Swift 中的 Closure 与 Objective-C 中的 Block 有一个显著的区别,就是 Closure 中的值类型变量默认是 mutable;而 Block 中的值类型变量默认是 copy,并且不可修改。
修改值类型
如果需要对值类型进行操作,在 Swift 只需要将它声明为变量(var)即可。
SWIFT
func makeIncrementor(amount: Int) -> () -> Int {
var runningTotal = 0
func incrementor() -> Int {
runningTotal += amount
return runningTotal
}
return incrementor
}
在 Objective-C 的 Block 中,想要引用并修改一个值类型的变量,则需要添加 __block 前缀:
OBJECTIVE-C
- (incrementor_t)makeIncrementor:(int)amount
{
__block int runningTotal = 0;
incrementor_t incrementor = ^() {
runningTotal += amount;
return runningTotal;
};
return incrementor;
}
也就是说,Swift 中 Closure 的默认行为就是 Objective-C 中 Block 的 __block 是一致的。