Need help understanding the use of defer in the LinkedList pop() method

What is defer accomplishing in the pop method?

@discardableResult
public mutating func pop() -> Value? {
  defer {
    head = head?.next
    if isEmpty {
        tail = nil 
    }
  }
  return head?.value
}

Thanks for the insight!

Let’s see. Here’s what I’ve come up with if you don’t use defer:

let returnVal = head?.value

head = head?.next
if isEmpty {
  tail = nil
}

return returnVal

In this case, using defer allows you to avoid instantiating a new variable.

Is this an aesthetic optimization, as in coding style, or is this a performance optimization? Seems the same work needs to be done to save the value explicitly with the instantiation or implicitly with the defer.

There should be a performance impact, but I’m not sure which way it’ll go. On one hand, using defer avoids introducing a new variable. On the other hand, the compiler will need to transform defer to a different set of instructions. Depending what that is, it could introduce some overhead.

I’m not sure which way is more performant!

Our tech editor made this change, and IMO it is mostly aesthetic. It is nice that we don’t have to worry about extra variables though.

Well I really don’t like it. I had composed my own question when I stumbled on this thread. I spent ages trying to explain why ‘head’ was changed and then returned with its previous value. I don’t know what ‘defer’ is doing and it looks like we’ve obtained some kind of side-effect. Aesthetics be damned!! This is a tutorial and it confused me. Please consider scrapping or adding a footnote in your next revision.

I am in agreement with tchelyzt. I remember hitting this point and focusing so much of my attention on ‘why did the author do this’ and away from the material I was reading the book for. After posting my comment here, I was not confident the author really understood the consequences of the code. That is not meant to disparage the author or the editor that made the change, I have used code out of habit because I know it just works; that doesn’t mean I took the time to process it’s full workings and value. That loss of trust made me pass on the rest of the book.

This is a learning resource, code should be clear and obvious for the beginner audience it is meant to focus on. If optimizations are necessary, they should be clearly explained.