Details of defer statement in Swift

Hello,
    From *The Swift Programming Language*, I learn the defer statements
execute in the reverse order that they appear in the program. And when
there are two or more defer statements in a loop(e.g. a for loop), defer
statements execute still in the reverse order that they appear, but in the
loop order that the loop statement executes. Code snippet is here(
https://swiftlang.ng.bluemix.net/#/repl/582421bfdee52b5745935771\).
    Early I saw this thread(
https://twitter.com/lexrus/status/796370747849441280\) from Twitter, I am
curious about defer statement's execute order. Can you tell more details
about it?

Best regards,

The manual says this:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Statements.html

A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in.

The scope of a for loop ends when the loop ends.

Regards,
Rien

Site: http://balancingrock.nl
Blog: http://swiftrien.blogspot.com
Github: Swiftrien (Rien) · GitHub
Project: http://swiftfire.nl

···

On 10 Nov 2016, at 08:32, Andrea VEH via swift-users <swift-users@swift.org> wrote:

Hello,
    From The Swift Programming Language, I learn the defer statements execute in the reverse order that they appear in the program. And when there are two or more defer statements in a loop(e.g. a for loop), defer statements execute still in the reverse order that they appear, but in the loop order that the loop statement executes. Code snippet is here(https://swiftlang.ng.bluemix.net/#/repl/582421bfdee52b5745935771\).
    Early I saw this thread(https://twitter.com/lexrus/status/796370747849441280\) from Twitter, I am curious about defer statement's execute order. Can you tell more details about it?

Best regards,
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Right, more specifically, it is the “static” scope that it is defined in. Go has a similar but different defer statement, which runs defer'd actions at the end of the current dynamic *function* scope. The Swift rules are simpler, more predictable, and are able to be implemented more efficiently.

-Chris

···

On Nov 9, 2016, at 11:45 PM, Rien <Rien@balancingrock.nl> wrote:

The manual says this:

The Swift Programming Language: Redirect

A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in.

The scope of a for loop ends when the loop ends.