Updating closures to Swift 3 - @escaping

前端 未结 2 1253
臣服心动
臣服心动 2020-11-30 23:35

I\'ve updated my code to Xcode 8.0 beta 6 but I got stuck with what seems to be about the new non escaping closure default. In the following code Xcode suggests to add

2条回答
  •  没有蜡笔的小新
    2020-12-01 00:00

    @noescape

    From xcode 8 beta 6 @noescape is the default. Prior to that, @escaping was the default. Anybody updating to swift 3.0 from previous versions might face this error.

    You can not store a @noescape closure inside a variable. Because if you can store a closure inside a variable, you can execute the closure from anywhere in your code. But @noescape states that the closure parameter can not escape the body of the function.

    This will give compiler error in Xcode 8

    class MyClass {
    
        var myClosure: (() -> ())?
    
        func doSomething(finishBlock: () -> ()) {
            myClosure = finishBlock    // ‼️ Error: Assigning non-escaping parameter 'finishBlock' to an @escaping closure
        }
    }
    

    This will compile ok (explicitly write @escaping)

    class MyClass {
    
        var myClosure: (() -> ())?
    
        func doSomething(finishBlock: @escaping () -> ()) {
            myClosure = finishBlock
        }
    }
    

    Benefits of @noescape:

    • Compiler can optimize your code for better Performance
    • Compiler can take care of memory management
    • There is no need to use a weak reference to self in the closure


    For details check out: Make non-escaping closures the default

提交回复
热议问题