Im testing Swift 2.0 and the new keyword defer
in a Playground:
func branch() -> String {
var str = ""
defer { str += "xxx" }
str += "1"
let counter = 3;
if counter > 0 {
str += "2"
defer { str += "yyy" }
str += "3"
}
str += "4"
return str
}
let bran = branch()
I expected bran
to be "123yyy4xxx"
, but it actually is "123yyy4"
Why did my defer (str += "xxx")
not work as expected?
With the setNeedsLayout() method, we can use defer to update the view. It may be necessary to call this method multiple times. By using defer , there's no worry about forgetting to execute the setNeedsLayout() method. defer will ensure that the method is always executed before exiting the scope.
The Swift defer statement allows you to execute code right before scope is exited (for example, before a function returns).
You use a defer statement to execute a set of statements just before code execution leaves the current block of code. The block of code might be a method, an if statement, a do block or a loop. The body of the defer statement runs regardless of how you leave the block, including throwing an error.
In Golang, the defer keyword is used to delay the execution of a function or a statement until the nearby function returns. In simple words, defer will move the execution of the statement to the very end inside a function.
A defer statement defers execution until the current scope is exited.
That what apple says. So the defer statement will be executed after return statement. That's why you cannot see the expected result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With