Swift 中的 finally 等价于什么

What's the equivalent of finally in Swift

我尝试使用 Swift2 中的错误处理模型。

do {
    try NSFileManager.defaultManager().removeItemAtPath("path")
} catch {
    // ...
} finally {
    // compiler error.
}

但是好像没有finally关键字出来there.How我可以在Swift.Any中实现try-catch-finally pattern欢迎帮助

您要找的是defer。它定义了一个代码块,直到执行刚要离开当前作用域时才执行,但它总是被执行。

func processFile(filename: String) throws {
    if exists(filename) {
        let file = open(filename)
        defer {
            close(file)
        }
        while let line = try file.readline() {
            /* Work with the file. */
        }
        // close(file) is called here, at the end of the scope.
    }
}

有关 defer 的更多详细信息,请查看 Apple Swift documentation, especially section "Specifying Clean-up Actions"

Swift 2 使用 defer 关键字

介绍了自己对此要求的看法
defer { 
    print("Do clean up here") 
}

finally = defer 在 Swift 2.

defer 关键字的文章

如果您认为 SWIFT 2.0 错误处理与异常是一回事,那您就误解了。
这不是异常,这是一个符合名为 ErrorType 的协议的错误。
该块的目的是拦截由抛出函数或方法抛出的错误。
基本上没有 finally,你可以做的是将你的代码包装在一个 defer 块中,这保证被执行并且范围结束。
这是来自 SWIFT 2 programming guide

的示例
func processFile(filename: String) throws {
    if exists(filename) {
        let file = open(filename)
        defer {
            close(file)
        }
        while let line = try file.readline() {
            /* Work with the file. */
        }
        // close(file) is called here, at the end of the scope.
    }
}

You use a defer statement to execute a set of statements just before code execution leaves the current block of code. This lets you do any necessary cleanup that should be performed regardless of whether an error occurred. Examples include closing any open file descriptors and freeing any manually allocated memory.

defer 在 Swift 2.0 中就像一个 finally,这意味着 swift 确保您在当前函数范围的末尾执行该延迟代码。 以下是我需要知道的一些要点: 1) 不管守卫会 returns 2) 我们可以编写多个延迟作用域

这是演示多个延迟的示例和输出:

    func myMethod()  {
    print("Message one")
    print("Message two")
    print("Message three")
    defer {
        print("defered block 3")
    }
    defer {
        print("defered block 2")
    }
    defer {
        print("defered block 1")
    }
    print("Message four")
    print("Message five")

}
 Output:
 Message one
 Message two
 Message three
 Message four
 Message five
 defered block 1
 defered block 2
 defered block 3

读这个:The defer keyword in Swift 2: try/finally done right

例如:

print("Step 1")

do {
    defer { print("Step 2") }
    print("Step 3")
    print("Step 4")
}

print("Step 5")

输出:

Step 1
Step 3
Step 4
Step 2
Step 5