Defer block is not executed

…衆ロ難τιáo~ 提交于 2019-12-04 04:00:49

问题


I have the following swift code executing in playground:

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

A()

I expected to see

Hello
World

Instead only the Hello is printed. Why is this? What am I missing?

Here is a better example:

enum MyError: ErrorType {
    case TriggerDefer
}

func throwsMyError() throws {
    let myzero = Int(arc4random_uniform(1))

    guard myzero > 1 else {
        throw MyError.TriggerDefer
    }
}

func A() throws {
    try throwsMyError()

    defer {
        print ("Hello World")
    }
}

As per the answers and comments, the correct way to do this (with an example) is

enum MyError: ErrorType {
    case TriggerDefer
}

func throwsMyError() throws {
    let myzero = Int(arc4random_uniform(1))

    print("Hello")

    guard myzero > 1 else {
        throw MyError.TriggerDefer
    }
}

func A() throws {        
    defer {
        print ("World")
    }

    try throwsMyError()
}

The output will now be

Hello
World

回答1:


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.




回答2:


Put the defer block before the scope is exited:

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

A()


来源:https://stackoverflow.com/questions/36169415/defer-block-is-not-executed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!