Defer block is not executed

后端 未结 2 1361
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 15:34

I have the following swift code executing in playground:

func A() {
    print ("Hello")
    guard 1 == 2 else {
        return
    }
    defer {
            


        
相关标签:
2条回答
  • 2021-01-18 16:01

    Put the defer block before the scope is exited:

    func A() {
        print ("Hello")
        defer {
            print ("World")
        }
        guard 1 == 2 else {
            return
        }
    }
    
    A()
    
    0 讨论(0)
  • 2021-01-18 16:15

    What you're missing is that deferis not magic. It is executable code, just like any other code. If the path of execution never encounters it, there is nothing to be deferred. This is why it should always be dead first in the block on whose exit it is to be executed — so that we guarantee that it is encountered.

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