I have the following swift code executing in playground:
func A() {
print ("Hello")
guard 1 == 2 else {
return
}
defer {
Put the defer
block before the scope is exited:
func A() {
print ("Hello")
defer {
print ("World")
}
guard 1 == 2 else {
return
}
}
A()
What you're missing is that defer
is not magic. It is executable code, just like any other code. If the path of execution never encounters it, there is nothing to be deferred. This is why it should always be dead first in the block on whose exit it is to be executed — so that we guarantee that it is encountered.