I have the following swift code executing in playground:
func A() {
print ("Hello")
guard 1 == 2 else {
return
}
defer {
print ("World")
}
}
A()
I expected to see
Hello
World
Instead only the Hello
is printed. Why is this? What am I missing?
Here is a better example:
enum MyError: ErrorType {
case TriggerDefer
}
func throwsMyError() throws {
let myzero = Int(arc4random_uniform(1))
guard myzero > 1 else {
throw MyError.TriggerDefer
}
}
func A() throws {
try throwsMyError()
defer {
print ("Hello World")
}
}
enum MyError: ErrorType {
case TriggerDefer
}
func throwsMyError() throws {
let myzero = Int(arc4random_uniform(1))
print("Hello")
guard myzero > 1 else {
throw MyError.TriggerDefer
}
}
func A() throws {
defer {
print ("World")
}
try throwsMyError()
}
The output will now be
Hello
World
The defer statement will keep your iOS application code running smoothly, even if a team member updates a method or adds a conditional statement. defer executes no matter how we exit and future proofs projects from changes that may alter the scope flow, reducing the possibility of an error.
A defer statement defers the execution of a function until the surrounding function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
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.
Put the defer
block before the scope is exited:
func A() {
print ("Hello")
defer {
print ("World")
}
guard 1 == 2 else {
return
}
}
A()
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