[swift-evolution] Pitch: Deinit for structs

David Owens II david at owensd.io
Wed Dec 23 15:21:42 CST 2015

This is something I asked for before, then I realized it wouldn’t work.

func helper(rs: ResourceHandle) {}

let resource = ResourceHandle()

result.doSomething() // error

Another example:

let x = Handle()

do {
  let y = x
} // resources are freed here as deinit is called

// x is not safe to use, and freed again when x goes out of scope

Everytime the struct value goes out of scope, the deinit would be called. The other option is to create move and copy semantics, as both would be required.

> Given Swift’s emphasis on value types

I think this is a mischaracterization, and one that I’ve made in the past. Swift’s emphasis in on clarity and providing you the mechanism to create things that are value-types for APIs that should behave like a value. However, that doesn’t mean that everything should a struct first.


> On Dec 23, 2015, at 1:07 PM, Charles Srstka via swift-evolution <swift-evolution at swift.org> wrote:
> Introduction:
> This is a rather simple proposal, requesting that structs allow the ‘deinit’ destructor, as classes currently do.
> Motivation:
> Sometimes it is necessary to create an object that wraps a network connection (that needs to be closed when the object is destroyed), or that writes to a file on the disk (that has to be closed when the object is destroyed). Often these objects will implement a close() method, but in the case that the user forgets to call this before the object is disposed of, it is good to call it in deinit just in case. However, deinit currently is available only to classes and not to structs. This means that value types currently cannot be used for network and file-backed constructs. Given Swift’s emphasis on value types, it seems that it would be good to add this functionality to value types.
> Proposed Solution:
> Allow the deinit destructor in structs.
> Impact on Existing Code:
> Should be no impact on existing code.
> Charles
> _______________________________________________
> 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/20151223/27bc0741/attachment.html>

More information about the swift-evolution mailing list