[swift-evolution] Proposal: Stored properties for enums

Jonathan Hise Kaldma info at hisekaldma.com
Wed Dec 9 14:28:56 CST 2015


Hi everyone,

Being able to associate values with enums is one of the features I love about Swift, especially together with the ability to make enums contain themselves. It makes it really easy to model tree-like structures, e.g. arithmetic expressions:

enum Expression {
    case Number(Double)
    case Variable(String)
    indirect case Unary(Operator, Expression)
    indirect case Binary(Operator, Expression, Expression)
}

This works great with Swift’s switch statement and let binding, and cuts out a lot of unnecessary code. But it breaks down if you need to keep track of more data for each tree node, e.g. if you’re making a parser and need to keep track of source location. This could easily be solved with stored properties:

enum Expression {
    case Number(Double)
    case Variable(String)
    indirect case Unary(Operator, Expression)
    indirect case Binary(Operator, Expression, Expression)

    var location: Int = 0
    var length: Int = 0
}

If the properties have default values, you would still get the regular enum initializer without properties like today:

let expr = .Number(3)

But you would also get a memberwise initializer with the properties after the associated values, which you can use if you the properties don’t have default values or if you just want to set them to something else.

let expr = .Number(3, location: 5, length: 1)

Other than that, enums would work just like they do today. Aside from the previous example, I think this would simplify a lot of use cases where you have a struct and an accompanying enum, so rather than:

struct Something {
  var type: SomethingType
  var width: Int
  var height: Int
}

enum SomethingType {
  case TypeA
  case TypeB
}

You would just have:

enum Something {
  case TypeA
  case TypeB

  var width: Int
  var length: Int
}

Feels very Swifty to me.

Thanks,
Jonathan


More information about the swift-evolution mailing list