[swift-evolution] Proposal: Stored properties for enums

Alex Lew alexl.mail+swift at gmail.com
Wed Dec 9 17:06:35 CST 2015

Interesting proposal! In Swift's docs on Pattern Matching (
the inability to easily access a value that is relevant to *all *cases of
an enum is explicitly mentioned as a minus of Swift's approach:

   - minus: needs boilerplate to project out a common member across
   multiple/all alternatives

The docs even mention that it might be worth providing "special
dispensations for ... projecting out common members."

This seems like an elegant solution to the all-alternatives problem (though
not the multiple-alternatives problem). +1

It is worth considering Frederick's point above that this essentially makes
struct X { ... } the same as enum X { case OnlyCase; ... }. Also, you'd
probably want to make sure that none of the associated values shared a name
with a stored property, to avoid confusion when initializing
(constructing?) new enums.

(Tommy, did you see the line in the original proposal suggesting that you'd
initialize stored properties as if they were additional named associated
values? E.g.: let expr = .Number(3, location: 5, length: 1). I think if you
were to reassign expr -- if it were a var -- you'd need to re-assign
location and length, too; they wouldn't transfer.)


On Wed, Dec 9, 2015 at 4:44 PM, Tommy van der Vorst via swift-evolution <
swift-evolution at swift.org> wrote:

> > None of the state-like nature of enums would be lost.
> >
> > enum Something {
> >  case StateA
> >  case StateB(Double)
> >  var prop: Int
> > }
> >
> > Would simply be a another way to write:
> >
> > enum Something {
> >  case StateA(Int)
> >  case StateB(Double, Int)
> > }
> Sure, but do we really need special syntax then? To me the above way of
> writing is much clearer on which data is available at what point than the
> variant with the separate 'var' declaration. You can even label the
> different values in the associated data tuple.
> Putting data shared across states in a separate 'var' declaration
> introduces some other issues as well: when an enum is reassigned (i.e. self
> = .StateB(...)), is the variable emptied somehow, or is it kept? How would
> you even initialize the value of a non-optional stored property that is not
> part of the case associated tuple (as the variables are not a 'requirement'
> of the case tuple, perhaps only optionals should be allowed)?
> /T
> _______________________________________________
> 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/20151209/cd2a8620/attachment.html>

More information about the swift-evolution mailing list