Skip to content

Commit a10b363

Browse files
authored
Include example of defer lexical scoping (#30)
This patch adds an example of how the defer statement is lexically scoped and will execute at the end of the scope, not the end of a function.
2 parents 4f6dc15 + 467d540 commit a10b363

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Sources/TSPL/TSPL.docc/ReferenceManual/Statements.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -817,6 +817,54 @@ This means that a `defer` statement can be used, for example,
817817
to perform manual resource management such as closing file descriptors,
818818
and to perform actions that need to happen even if an error is thrown.
819819

820+
The *statements* in the `defer` statement
821+
are executed at the end of the scope that encloses the `defer` statement.
822+
823+
```swift
824+
func f(x: Int) {
825+
defer { print("First defer") }
826+
827+
if x < 10 {
828+
defer { print("Second defer") }
829+
print("End of if")
830+
}
831+
832+
print("End of function")
833+
}
834+
f(x: 5)
835+
// Prints "End of if"
836+
// Prints "Second defer"
837+
// Prints "End of function"
838+
// Prints "First defer"
839+
```
840+
841+
842+
@Comment {
843+
```swifttest
844+
-> func f(x: Int) {
845+
defer { print("First defer") }
846+
847+
if x < 10 {
848+
defer { print("Second defer") }
849+
print("End of if")
850+
}
851+
852+
print("End of function")
853+
}
854+
f(x: 5)
855+
<- End of if
856+
<- Second defer
857+
<- End of function
858+
<- First defer
859+
```
860+
}
861+
862+
In the code above,
863+
the `defer` in the `if` statement
864+
executes before the `defer` declared in the function `f`
865+
because the scope of the `if` statement ends
866+
before the scope of the function.
867+
820868
If multiple `defer` statements appear in the same scope,
821869
the order they appear is the reverse of the order they're executed.
822870
Executing the last `defer` statement in a given scope first

0 commit comments

Comments
 (0)