[swift-evolution] [Proposal] Scoped resources (like C# using statement)
Chris Lattner
clattner at apple.com
Tue Dec 29 22:15:52 CST 2015
On Dec 29, 2015, at 8:02 PM, Trent Nadeau via swift-evolution <swift-evolution at swift.org> wrote:
> Doing this manually is possible using `defer` statements among other options, but this is error prone as a `defer` can be forgotten, `lock`/`unlock` calls for two locks can be switched due to a typo, etc. Having a dedicated language construct for this common case makes it easier to read and write while making code shorter and clearer.
>
> ```swift
> do {
> lock.enterScope()
> defer { lock.exitScope() }
>
> let file = try getFileHandle()
> file.enterScope()
> defer { file.exitScope() }
>
> // statements
> }
We have another pattern that types can use, which is:
lock.withThisLockHeld {
… stuff ...
}
This can be done today with trailing closures. Other examples of this are “autoreleasepool” and withUnsafePointer (for other reasons).
-Chris
More information about the swift-evolution
mailing list