Anonymous Enums (Updated)


(Yong hee Lee) #1

Hi, I have a proposal.

enum Foo {
  case foo,bar
}

func test(a:Foo) {
  // …
}

test(.bar)

If I use an enum only as a parameter of a function, the name of enum is redundant.

so I suggest a compact version like below.

func test(a:[foo|bar]) {
  // ...
}

test(.bar)

func adjustTemperature(temp:[low|normal|high]) {
  // ...
}

adjustTemperature(.high)

I think this is very useful.
What do you think?

···

————————————————————————————

I’ve added an explanation.

Benefits

Anonymous enums let you see all enum options at a glance.

func adjustTemperature(temp:[low|normal|high]) { … }
In case of normal enums, callers should check inside of the enum interface.

Anonymous enums encourage switch-case coding style.

// Bool variables lead to use if-else clauses.

var switchIsOn : Bool = true

if switchIsOn {
  //
  // ...
  //
} else {
  //
  // ...
  //
}

// Anonymouse enums lead to use switch-case clauses.

var switchState: [on|off] = .on

switch(switchState) {
case .on :
  //
  // ...
  //
case .off :
  //
  // ...
  //
}

// i think the switch-case is a much better option for readability because you can label each cases. If your code is very long and uses many nested if-clauses, it makes huge differences.

Generally, you don’t use anonymous enums as an alternative of normal enums.
I think enum is a structure but, anonymous enum is just a flag variable type.

You can make an anonymouse enum variable without thinking that you are making a new structure and increasing complexity.
Therefore, anonymous enums can replace bool flags easily without a mental barrier.

“Small differences make big changes”