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

Austin Zheng austinzheng at gmail.com
Wed May 4 16:46:19 CDT 2016


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

Thanks for your time, and have a great day!

Austin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160504/1fa85249/attachment.html>


More information about the swift-evolution mailing list