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

Kevin Ballard kevin at sb.org
Wed Dec 30 18:30:39 CST 2015


If we need some way to say "this local variable should extend to the end
of the scope", the most obvious (to me) way to do that is to introduce
an attribute that you can add to the variable declaration. This would be
similar to Obj-C's __attribute__((objc_precise_lifetime)), although not
quite as wordy. Although I am tempted to say we should go with `defer {
_ = val }` because I always like when you can re-use existing language
features; that does require we define `_ = val` as extending the
lifetime of val to that point, but as I said before I think that's a
perfectly reasonable thing to do.

-Kevin Ballard

On Wed, Dec 30, 2015, at 03:23 PM, Matthew Johnson wrote:
>
>> On Dec 30, 2015, at 5:19 PM, Kevin Ballard via swift-evolution <swift-
>> evolution at swift.org> wrote:
>>
>> On Wed, Dec 30, 2015, at 03:12 PM, Kevin Wooten via swift-
>> evolution wrote:
>>>>>
>>>>> Another possibility I've thought of is defining `defer { val }` to
>>>>> guarantee that val remains alive until the defer fires on scope
>>>>> exit. That might let us leave `defer` as the one "guarantee
>>>>> something happens exactly at scope exit" language construct.
>>>
>>> What about this…
>>>
>>> defer let val = grabOrCreateSomething() {  return; }
>>>
>>> Seems natural once you learn guard.
>>
>> Natural? I have no idea what you're expecting that expression to
>> actually do. What is a "defer let”?
>
> I think the idea is that a local variable declared with a `defer`
> modifier has its lifetime extended until the scope exits.  It is a
> slightly more compact version of what Joe suggested.  But I agree that
> it has potential for confusion - it reads like it is deferring the
> initialization of `val` until the scope exits which would be rather
> pointless.
>
> I do like the idea of making the extended lifetime part of the
> local variable declaration but I’m not sure about how this specific
> syntax reads.
>
>>
>> -Kevin
>>
>>
>> _______________________________________________
>> swift-evolution mailing list swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151230/9a8341e9/attachment.html>


More information about the swift-evolution mailing list