[swift-evolution] [Pitch] Reference equivalent to value-type 'enum'

Matthew Johnson matthew at anandabits.com
Wed May 4 17:25:33 CDT 2016


> On May 4, 2016, at 4:46 PM, Austin Zheng via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hello swift-evolution:
> 
> Based on recent conversations on the list, I'd like to float a trial balloon: an "enum class" kind which is analogous to classes in the same way existing enums are to structs. This is a data type which allows the user to define a number of cases, like enums, and can participate in pattern matching and exhaustivity analysis. Instances of an enum class are reference types, which enables (for example) graph nodes with a built-in concept of identity.
> 
> To be slightly more fanciful, perhaps such a kind could be treated as an 'almost-final' class, with each case being a nested type which is defined as a final subclass of the enum class. Cases could then define their own behavior:
> 
> enum class GraphNode {
>   case Node(left: GraphNode, right: GraphNode) {
>     override func foo() { ... }
>     func nodeSpecificMethod() { ... }
>   }
> 
>   case Leaf {
>     override func foo() { ... }
>     func leafSpecificMethod() { ... }
>   }
> 
>   func foo() { ... }
> }
> 
> let x : GraphNode = GraphNode.newEmptyTree()
> let y : GraphNode = GraphNode.Node(l, r)
> let z : GraphNode = GraphNode.Leaf()
> let a : GraphNode.Leaf = GraphNode.Leaf()
> 
> Enum classes would not be subclassible, and extensions would not be able to define new cases (as is the case with normal enums at the present time).
> 
> My superficial analysis seems to suggest that this would solve two issues: providing a reference-semantics type with all the pattern matching functionality of current enums, and providing a construct for modeling case-class style ADTs where each case should be treated as a subtype (as has been occasionally proposed).
> 
> I would like feedback as to:
> - Whether this is something that would be useful enough to justify additional language features
> - Whether this is something that would be theoretically well-founded and elegant
> 

This is definitely an idea worth exploring.  I am interested in hearing from folks who have experience with Scala case classes.  How have you found them useful in ways that Swift’s current enums do not address?  


> Thanks for your time, and have a great day!
> 
> Austin
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list