iOS中块(Objective-C)和闭包(Swift)之间的区别

Difference between block (Objective-C) and closure (Swift) in iOS

在教程中,虽然闭包比块更容易,而且避免了块和内存管理的复杂性,但在功能上都是相同的,我已经看过很多教程,但是除了这些,我没有swift的" closure "和Objective-C " block "之间的区别。


摘录自:Apple Inc.?将Swift与Cocoa和Objective-C一起使用? iBooks:

a€?Swift closures and Objective-C blocks are compatible, so you can pass Swift closures to Objective-C methods that expect blocks. Swift closures and functions have the same type, so you can even pass the name of a Swift function.

Closures have similar capture semantics as blocks but differ in one key way: Variables are mutable rather than copied. In other words, the behavior of __block in Objective-C is the default behavior for variables in Swift.a€?


稍有差异。提到一个;变量被捕获为变量,而不是值。这可能是有用的,也可能是陷阱。重要的是,您可以在Swift闭包中定义捕获列表,因此,如果在捕获列表中包含self.property,则将捕获该属性的值,而不是self。这也简化了捕获弱变量的过程。


显示差异的实际代码示例:

这确实可以编译:

1
let x : @convention(swift) (inout Int) -> ()

这不是:

1
let y : @convention(block) (inout Int) -> ()

,错误为(inout Int) -> () is not representable in Objective-C