What is the difference between a pending statement and a statement just before a return?
All the difference in the world. The defer
is executed after return! This allows you to do things that cannot be done in any other way.
For example, you can return a value and then change it. Apple uses this trick quite regularly; here, for example, is the code from the sequence documentation showing how to write your own sequence:
struct Countdown: Sequence, IteratorProtocol { var count: Int mutating func next() -> Int? { if count == 0 { return nil } else { defer { count -= 1 } return count } } }
If you wrote it like
count -= 1 return count
... it would break; we do not want to decrease count
and then return it, we want to return count
and then decrease it.
In addition, as already indicated, the defer
is executed no matter how you exit. And this works regardless of whether you exit the current scope, which may not include return
at all; defer
works for function body, while block, if construct, do block, and so on. The only return
is not the only way to get out of such a sphere! Your method may have multiple return
, and / or you may throw an error, and / or you may have break
, etc. Etc., Or you can just reach the last line of scope; defer
is executed whenever possible. Writing the same code “manually” to cover all possible outputs can be very error prone.
source share