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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26374792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:12:34  来源:igfitidea点击:

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

iosobjective-cswiftclosuresobjective-c-blocks

提问by Sujay

In tutorials it's written that functionally both are same even closure is more easier then block and its avoided the complexity of block and memory management, I've gone through many tutorials but except these I'm not getting the difference between swift's "closure" and Objective-C "block".

在教程中写到,两者在功能上是相同的,即使闭包比阻塞更容易,并且它避免了块和内存管理的复杂性,我已经阅读了很多教程,但除了这些我没有得到 swift 的“闭包”和Objective-C“块”。

回答by GoZoner

Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks:

摘自:Apple Inc. “将 Swift 与 Cocoa 和 Objective-C 结合使用”。电子书:

“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.”

“Swift 闭包和 Objective-C 块是兼容的,因此您可以将 Swift 闭包传递给需要块的 Objective-C 方法。Swift 闭包和函数具有相同的类型,因此您甚至可以传递 Swift 函数的名称。

闭包具有与块相似的捕获语义,但在一个关键方面有所不同:变量是可变的而不是复制的。换句话说,Objective-C 中 __block 的行为是 Swift 中变量的默认行为。”

回答by gnasher729

Slight differences. One was mentioned; variables are captured as variables, not as values. Which can be either useful or a trap. Importantly you can define a capture list in a Swift closure, so if you include self.property in the capture list, then the value of that property is captured, and not self. That also simplifies capturing weak variables.

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

回答by Kametrixom

To show an actual code example of the differences:

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

This does compile:

这确实编译:

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

This does not:

这不会:

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

with the error (inout Int) -> () is not representable in Objective-C

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