延迟块未执行 [英] Defer block is not executed

查看:80
本文介绍了延迟块未执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在操场上执行以下快速代码:

I have the following swift code executing in playground:

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

我希望看到

Hello
World

而仅 Hello 已打印。为什么是这样?我缺少什么?

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")
    }
}




根据答案和评论,正确的方法(例如)是


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输出现在将是

Hello
World


推荐答案

您缺少的是 defer 不是魔术。就像任何其他代码一样,它是可执行代码。如果执行路径从未遇到过,则没有什么可推迟的。这就是为什么在执行退出的代码块中始终将其先死的原因,以便我们保证遇到

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.

这篇关于延迟块未执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆