Defer is used to make code *always* run, even if the function terminates early. Imagine:
func doSomethingWith(x: Int) {
print(“1”)
defer { print(“2") }
if x > 3 { defer { print(“yay”); return }
print(“3”)
}
Now print(“2”) will always happen, even if the if is true. Placing it at the
end this will not be the case. The “yay” will only be printed in the case of
the if.
In general we can not place the defer at the end, because it only should run if
the code “comes by” the call.
Regards,
Nicky
> On 2 jan. 2016, at 15:25, Maury Markowitz via swift-evolution
> <[email protected]> wrote:
>
> I'm confused about 'defer'. Not the purpose, the chosen syntax.
>
> func confusing() {
> print("1")
> defer { print("2") }
> print("3")
> }
>
> Produces 1,3,2. Trying to describe what is happening here is non-trivial...
> it runs line 1, then we put line 2 on a stack, then line three runs, then we
> pop the stack... what?! And stepping through it in the debugger... ugh.
>
> Unless I missed something obvious, wouldn't placing "code that always has to
> run at the end" actually *at the end* not make more sense? Like this...
>
> func clear() {
> print("1")
> print("3")
>
> always { print("2") }
> }
>
> Not only is the code clearly expressing its intent, the actual execution is
> following the source.
>
>
> _______________________________________________
> swift-evolution mailing list
> [email protected]
> https://lists.swift.org/mailman/listinfo/swift-evolution
signature.asc
Description: Message signed with OpenPGP using GPGMail
_______________________________________________ swift-evolution mailing list [email protected] https://lists.swift.org/mailman/listinfo/swift-evolution
