简体   繁体   English

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

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

在教程中,它写的功能都是相同的,甚至闭包更容易阻塞,它避免了块和内存管理的复杂性,我已经经历了很多教程,但除了这些我没有得到swift的“闭包”和Objective-C“阻止”。

Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks: 摘录自:Apple Inc.“将Swift与Cocoa和Objective-C结合使用。”iBooks:

“Swift closures and Objective-C blocks are compatible, so you can pass Swift closures to Objective-C methods that expect blocks. “Swift闭包和Objective-C块是兼容的,因此您可以将Swift闭包传递给期望块的Objective-C方法。 Swift closures and functions have the same type, so you can even pass the name of a Swift function. Swift闭包和函数具有相同的类型,因此您甚至可以传递Swift函数的名称。

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.” 换句话说,Objective-C中__block的行为是Swift中变量的默认行为。“

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. 重要的是,您可以在Swift闭包中定义捕获列表,因此如果在捕获列表中包含self.property,则捕获该属性的值,而不是self。 That also simplifies capturing weak variables. 这也简化了捕获弱变量的过程。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM