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

前端 未结 3 845
北荒
北荒 2020-12-13 00:02

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 t

相关标签:
3条回答
  • 2020-12-13 00:26

    Excerpt From: Apple Inc. “Using Swift with Cocoa and 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 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.”

    0 讨论(0)
  • 2020-12-13 00:38

    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.

    0 讨论(0)
  • 2020-12-13 00:40

    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

    0 讨论(0)
提交回复
热议问题