何時使用延期宣告
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