defer
大约 1 分钟
defer
defer关键字在Swift 2.0中引入,但在项目中仍然很少使用。
defer语句
defer语句用于在将程序控制转移到语句出现的范围之外之前执行代码。
func updateImage() {
defer { print("Did update image") }
print("Will update image")
imageView.image = updatedImage
}
// Will update Image
// Did update image
多个defer语句的执行顺序
如果多个语句出现在同一范围内,出现的顺序与执行顺序相反。最后定义的语句是第一个要执行的语句:
func printStringNumbers() {
defer { print("1") }
defer { print("2") }
defer { print("3") }
print("4")
}
/// Prints 4, 3, 2, 1
常见的用例
最常见的用例是打开和关闭上下文,例如在处理文件访问时。访问完成后,需要关闭FileHandle。可以从推迟声明中受益,以确保不会忘记这样做:
func writeFile() {
let file: FileHandle? = FileHandle(forReadingAtPath: filepath)
defer { file?.closeFile() }
// Write changes to the file
}
确保回调
该语句的更高级用法是确保在完成回调中返回结果值。这非常方便,因为很容易忘记触发此回调。 确保始终执行完成处理程序,并验证结果值。每当结果值为nil,就会抛出致命错误,应用程序就会失败。
func getData(completion: (_ result: Result<String>) -> Void) {
var result: Result<String>?
defer {
guard let result = result else {
fatalError("We should always end with a result")
}
completion(result)
}
// Generate the result..
}