@noescape attribute in Swift 1.2

后端 未结 3 1915
生来不讨喜
生来不讨喜 2020-12-04 07:03

There is a new attribute in Swift 1.2 with closure parameters in functions, and as the documentation says:

This indicates that the parameter is only

3条回答
  •  独厮守ぢ
    2020-12-04 07:29

    One way to think about it, is that EVERY variable inside of the @noescape block doesn't need to be Strong (not just the self).

    There are also optimizations possible since once a variable is allocated that then wrapped in a block, it can't just be normally deallocated at the end of the function. So it must be allocated on the Heap and use ARC to deconstruct. In Objective-C, you have to use the "__block" keyword to insure that the variable is created in a block friendly way. Swift will automatically detect that so the keyword isn't needed, but the cost is the same.

    If the variables are being passed to a @nosecape block, than they can be stack variables, and don't need ARC to deallocate.

    The variables now don't even need to be zero-referencing weak variables (which are more expensive than unsafe pointers) since they will be guaranteed to be "alive" for the life of the block.

    All of this results in faster and more optimal code. And reduces the overhead for using @autoclosure blocks (which are very useful).

提交回复
热议问题