Wednesday, March 22, 2023

Swift Proposal: Noncopyable Structs and Enums

SE-0390:

All currently existing types in Swift are copyable, meaning it is possible to create multiple identical, interchangeable representations of any value of the type. However, copyable structs and enums are not a great model for unique resources. Classes by contrast can represent a unique resource, since an object has a unique identity once initialized, and only references to that unique object get copied. However, because the references to the object are still copyable, classes always demand shared ownership of the resource. This imposes overhead in the form of heap allocation (since the overall lifetime of the object is indefinite) and reference counting (to keep track of the number of co-owners currently accessing the object), and shared access often complicates or introduces unsafety or additional overhead into an object’s APIs. Swift does not yet have a mechanism for defining types that represent unique resources with unique ownership.

[…]

We propose to allow for struct and enum types to declare themselves as noncopyable, using a new syntax for suppressing implied generic constraints, ~Copyable. Values of noncopyable type always have unique ownership, and can never be copied (at least, not using Swift’s implicit copy mechanism). Since values of noncopyable structs and enums have unique identities, they can also have deinit declarations, like classes, which run automatically at the end of the unique instance’s lifetime.

Previously:

4 Comments RSS · Twitter · Mastodon

Complexity begets complexity begets complexity, all for things that are easily accomplished by other means.

So `class` is insufficient for singletons because they want to avoid heap allocation of a single value?

Swift isn't going to be finished until every feature duplicates every other feature's features.

This language looks like a bloated mess.

The evolution of Swift has made me reevaluate my prior statements of C++ being overly complex.
It is actually starting to look pretty nice and simple in comparison.

Leave a Comment