TheRightLane on Coding

Using defer in Swift in 2 minutes

September 26, 2017

"Subtly useful" is not something that is usually said about programming constructs. But "defer" is without doubt a perfect candidate for being subtly useful.

Why?

Defer is a way of telling a code block to execute when the function exits. If you haven't used defer before it can be a little confusing to know where or why you should use it.

Where? Why?

Let's say you have a function like this

func doSomething() {
    guard let b = a
        else { return }
    if b == 1 {
        print("Yay")
        return
    }
    print("Boo")
}

Now, let's suppose, for some reason, you want to print "done" whenever you exit the function.

That's dumb!

It's an example! It doesn't need to make sense.

Without defer

func doSomething() {
    guard let b = a
        else { 
            print("done")
            return 
        }
    if b == 1 {
        print("Yay")
        print("done")
        return
    }
    print("Boo")
    print("done")
}

Pretty awful right? Tricky to maintain too!

Now, with defer

func doSomething() {
    defer {
        print("done")
    }
    guard let b = a
        else { return }
    if b == 1 {
        print("Yay")
        return
    }
    print("Boo")
}

Better, right?

Ok, when do I actually use this

Callbacks, cleanup, and notifications are the most obvious. The best part about defer is that no matter how complex your function you are guaranteed that your defer block will be called on exit. My rule is if there are more than two points where my function exits then it is time to consider a defer.

Knock 'em dead!

Lane Thompson