Preface
Everyone should know that in some languages, there are control statements such as try/finally, such as Java.
This statement allows us to execute the code that must be executed in the finally code block, no matter how we make trouble before.
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 shown in the above example, after printing out "CheckPoint 2", "Clean up here", but "CheckPoint 3". This is what defer does, it doesprint("Clean up here")
Delay.
Let's look at another I/O example:
// pseudocodefunc writeSomething() { let file = OpenFile() let ioStatus = fetchIOStatus() guard ioStatus != "error" else { return } () closeFile(file) }
The above example is a pseudo-code for I/O operations. If the obtained ioStatus is normal, then there is no problem with this method.
If ioStatus gets an error, it will be caught by the guard statement and execute the return operation.
That waycloseFile(file)
It will never be executed, and a serious bug will occur like this.
Let's see how to solve this problem with defer:
// pseudocodefunc writeSomething() { let file = OpenFile() defer { closeFile(file) } let ioStatus = fetchIOStatus() guard ioStatus != "error" else { return } () }
we willcloseFile(file)
Put it in the defer code block, so that even if ioStatus is an error, the code in the defer will be executed first before executing the return, which ensures that no matter what happens, the file will be closed in the end.
It should be noted that although the content of defer will be executed before return, if the defer is defined after return, the content of deft will still not be executed, that is, the defer keyword must appear earlier than return.
After return:
var str = "Hello, playground" func show() { print("Here is about to be postponed(But it will definitely)Executed code") } func test() { if >= 2 { print("Out of the execution of this method") return } defer { show() } } test() // Output result: Execute the method
Put before return:
var str = "Hello, playground" func show() { print("Here is about to be postponed(But it will definitely)Executed code") } func test() { defer { show() } if >= 2 { print("Out of the execution of this method") return } } test() // Output result: Execute the method Here is about to be postponed(But it will definitely)Executed code
Summarize
The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.