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

James Froggatt conductator at ntlworld.com
Thu May 5 03:25:10 CDT 2016


I haven't tried any languages which have anything like this, but I support the idea of bringing real properties and single-case functions to enums in this way. Using properties rather than parameterised values will prevent pattern matching in switch statements to get those properties, but the idea of generic parameters being able to hold values gets thrown about a lot, which could eventually provide that functionality to enum classes, making pure enums a subset of their functionality.

If there's one fault I can see with this proposal, it's that it's lacking a value-type equivalent, an ‘enum struct’. ;)

------------ Begin Message ------------ 
Group: gmane.comp.lang.swift.evolution 
MsgID: <CANGnqV2O8eEo=Kw+fd9phpE_KT0NyvstrgNSHBBtTrj6gnpH7Q at mail.gmail.com> 

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



------------- End Message ------------- 



From James F


More information about the swift-evolution mailing list