The defer keyword in Swift postpones the example elaboration

  • 2020-06-03 08:33:59
  • OfStack

preface

As you may know, in some languages there are control statements like try/finally, such as Java.

This statement allows us to execute the code that must be executed in the finally block, no matter how much fuss we make.

In Swift 2.0, Apple provides the defer keyword, allowing us to achieve the same effect.


func checkSomething() {
 print("CheckPoint 1")
 doSomething()
 print("CheckPoint 4")
}
 
func doSomething() {
 print("CheckPoint 2")
 defer {
 print("Clean up here")
 }
 print("CheckPoint 3")
} 
checkSomething() // CheckPoint 1, CheckPoint 2, CheckPoint 3, Clean up here, CheckPoint 4

As you can see from the above example, instead of printing out "Clean up here" after printing out "CheckPoint 2", you print out "CheckPoint 3". This is what defer does and it works print("Clean up here") Delay.

Let's look at another example of I/O:


//  Pseudo code 
func writeSomething() {
 let file = OpenFile()
 let ioStatus = fetchIOStatus()
 guard ioStatus != "error" else {
  return
 }
 file.write()
 closeFile(file) 
}

The above example is a pseudocode for the I/O operation. If the acquired ioStatus is normal, then the method is ok.

If ioStatus gets error, the guard statement catches the return operation,

so closeFile(file) It will never be implemented, and a serious Bug is thus created.

Here's how to solve this problem with defer:


//  Pseudo code 
func writeSomething() {
 let file = OpenFile()
 defer {
  closeFile(file)
 }
 let ioStatus = fetchIOStatus()
 guard ioStatus != "error" else {
  return
 }
 file.write()
}

We will be closeFile(file) Put it in the defer block so that even though ioStatus is error, the code in defer is executed before return, ensuring that whatever happens, the file is closed at the end.

It is important to note that while defer's content will be executed before return, if defer is defined after return, then defter's content will not be executed, that is, the defer keyword must predate return.

After return:


var str = "Hello, playground"
func show() {
 print(" Here is the coming delay ( but 1 will ) Executed code ")
}
func test() {
 if str.characters.count >= 2 {
  print(" Jump out of the execution of the method ")
  return
 }
 defer {
  show()
 }
}
test() //  The output :  Jump out of the execution of the method 

Before return:


var str = "Hello, playground"
func show() {
 print(" Here is the coming delay ( but 1 will ) Executed code ")
}
func test() {
 defer {
  show()
 }
 if str.characters.count >= 2 {
  print(" Jump out of the execution of the method ")
  return
 }
}
test() //  The output :  Jump out of the execution of the method   Here is the coming delay ( but 1 will ) Executed code 

conclusion


Related articles: