何时使用延期声明

defer 语句由一个代码块组成,该代码块将在函数返回时执行,并应用于清理。

由于 Swift 的 guard 语句鼓励一种早期回归的方式,可能存在许多可能的回归路径。defer 语句提供清理代码,每次都不需要重复。

它还可以在调试和分析期间节省时间,因为可以避免由于忘记清理而导致的内存泄漏和未使用的开放资源。

它可用于在函数末尾释放缓冲区:

func doSomething() {
    let data = UnsafeMutablePointer<UInt8>(allocatingCapacity: 42)
    // this pointer would not be released when the function returns 
    // so we add a defer-statement
    defer {
        data.deallocateCapacity(42)
    }
    // it will be executed when the function returns.
    
    guard condition else { 
        return /* will execute defer-block */ 
    }
       
}   // The defer-block will also be executed on the end of the function.

它还可以用于在函数末尾关闭资源:

func write(data: UnsafePointer<UInt8>, dataLength: Int) throws {
    var stream:NSOutputStream = getOutputStream()
    defer {
        stream.close()
    }

    let written = stream.write(data, maxLength: dataLength)
    guard written >= 0 else { 
        throw stream.streamError! /* will execute defer-block */ 
    }
    
}    // the defer-block will also be executed on the end of the function