[swift-evolution] [Proposal] Scoped resources (like C# using statement)

Trent Nadeau tanadeau at gmail.com
Tue Dec 29 22:24:53 CST 2015


While useful, that pattern doesn't seem to compose well. What if you need
two locks? Would that be:

lock1.withThisLockHeld {
    lock2.withThisLockHeld {
        // statements
    }
}

If so, it seems like it has the "pyramid of doom" issue that prompted
allowing `if let` to have multiple bindings.

In addition to the possible indentation and vertical space issue, you need
to look up if and how each resource type does this. I believe this is a
general enough pattern that it deserves language support. I think an
analogy to the current situation would be if each collection type had its
own way to iterate (Array.forEach, Set.withEachElement, etc.) instead of
having for-in.

On Tue, Dec 29, 2015 at 11:15 PM, Chris Lattner <clattner at apple.com> wrote:

> 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
>
>


-- 
Trent Nadeau
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151229/57b8b26f/attachment.html>


More information about the swift-evolution mailing list