控制流 / 其他运算符

var sum10 = 0
if sum10 < 10 {
    defer {
        print("sum10: \(sum10)")
    }
    for i in 1...10 {
        sum10 += i
    }
}
// Prints "sum10: 55" 


Unlike control-flow constructs like if and while, which let you control whether part of your code is executed or how many times it gets executed, defer controls when a piece of code is executed. You use a defer block to write code that will be executed later, when your program reaches the end of the current scope.

In the example above, the code inside of the defer block is executed before exiting the body of the if statement. First, the code in the if statement runs, which calculates the sum of the numbers 1 through 10. Then, before exiting the if statement’s scope, the deferred code is run, which prints sum10.