根据 Apple Swift 文档defer
无论执行如何离开当前代码块,无论它是因为抛出错误还是因为诸如 return 或 break 之类的语句而离开,此语句都允许您执行任何应该执行的必要清理。
但是这段代码:
enum SomeError: ErrorType {
case BadLuck
}
func unluckey() throws {
print("\n\tunluckey() -> someone will have a bad day ;)\n")
throw SomeError.BadLuck
}
func callsUnluckey() throws {
print("callsUnluckey() -> OPENING something")
defer {
print("callsUnluckey() -> CLOSEING something")
}
print("callsUnluckey() -> WORKING with something")
try unluckey()
print("callsUnluckey() -> will never get here so chill...")
defer {
print("callsUnluckey() -> why this is not getting called?")
}
}
do {
try …
Run Code Online (Sandbox Code Playgroud)