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

Joe Groff jgroff at apple.com
Thu Dec 31 18:46:58 CST 2015


> On Dec 31, 2015, at 4:26 PM, Kevin Ballard <kevin at sb.org> wrote:
> 
> On Thu, Dec 31, 2015, at 01:40 PM, Michel Fortin wrote:
>> Le 30 déc. 2015 à 16:40, Kevin Ballard via swift-evolution <swift-evolution at swift.org> a écrit :
>>> On Wed, Dec 30, 2015, at 01:33 PM, Joe Groff 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.
>>> 
>>> Oh that's cute. I'd probably want to say `defer { _ = val }` though, to make it obvious that this is intentional.
>> 
>> Or you could make it even more obvious what this is by giving that feature a name. For instance:
>> 
>> 	defer { _fixLifetime(val) }
>> 
>> The good thing about this one is that it already works, because that's what `withExtendedLifetime` does internally. Also, if you search a bit, you'll end up here with a nice explanation of what that function does.
>> https://github.com/apple/swift/blob/8d9ef80304d7b36e13619ea50e6e76f3ec9221ba/stdlib/public/core/LifetimeManager.swift#L45
>> 
>> So why not simply remove the underscore?
> 
> Because it's not a very good API? Having some magic function called `fixLifetime()` that keeps values alive is a little weird. `withExtendedLifetime()` is also slightly weird, but it makes more sense than fixLifetime() does, since withExtendedLifetime() is the specific solution to the problem of "I need to ensure this value remains alive for this entire scope because reasons".
> 
> I'd much rather just see the syntax `_ = val` be converted into `Builtin.fixLifetime(val)` because the only reason to write an expression like that is because you want to make sure the value is still alive at that point (that and because it's not unreasonable for people to assume that `_ = val` will keep the value alive, so it would be nice to make that assumption actually be correct).

I don't think this is obviously true. `val` could be a computed property you just want to force the side effects for. (Computed properties with side effects maybe aren't a great idea, but there are some in AppKit/UIKit.)

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151231/af1b9778/attachment-0001.html>


More information about the swift-evolution mailing list