[swift-users] The value of enums

Erica Sadun erica at ericasadun.com
Sun Nov 6 14:04:59 CST 2016

> On Nov 6, 2016, at 4:07 AM, Tino Heth via swift-users <swift-users at swift.org> wrote:
> Enums are a fundamental part of Swift, so I guess they won't change much — but I wonder if anyone shares my observations in real-life use…
> Afair, there are three different types of enums:
> - Enums with raw values
> - enums with associated objects
> - Plain enums (no underlying value)
> I use the first type quite often (as a convenient way to create string constants, or for serialization), but see no real value in plain enums (they offer nothing over enums backed with a raw value).
> The second type is special:
> It looks like a really cool concept, and and I started several designs based on them — just to realize later that structs and classes are a better fit.
> My conclusion so far is that enums perform bad as soon as you want to attach additional data or behavior; one or two computed properties are ok, but those switch-statements quickly become a burden.
> There are some options to work around this problem, but I guess I'll just stay away from enums with associated objects by default (with the exception of error-types — imho those can be modeled quite nicely).
> So, that's my current perception, and I'm curious if others had similar experiences — or, even more interesting, completely different observations and elegant solutions based on enums.


* Great for umbrella type implementation
* Plain enums: perfect for enumeratable states and defining roles.
* Associated types: I use them mostly for Result type, but also handy for things like 
  JSON parsers,  which are Swift's mandated follow-on to "Hello World"
* Enums with raw values: I mostly stick to stringity ones, where there's a state or role but
  I want to have easy access to the name as well as the role, and integer ones, where I can
  repurpose the number elsewhere
* I really love using enums with switch statements, and compiler guarantees of case 

I'd put forth that enum cases should be few, simple, and focused. They should not be 
used as flags.  When used well, they should feel obvious and integrate well into 
switch statements. 

-- E

More information about the swift-users mailing list