Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum of string type vs struct with static constant

It seems like when the need to use enum (of string type) arise, it can also be achieved using struct using static fields.

e.g.

enum Test: String {
  case TestCase1
  case TestCase2
  case TestCase3
}

or

struct Test {
  static let TestCase1 = "TestCase1"
  static let TestCase2 = "TestCase2"
  static let TestCase3 = "TestCase3"
}

When is the enum approach preferred over the other, or vice versa?

like image 795
Boon Avatar asked Mar 11 '16 02:03

Boon


1 Answers

They're both perfectly viable.

I used to argue that the enum approach was less flexible because you had to ask explicitly for the raw value in order to reach the underlying string, but I no longer think that, because there are ways to extend classes such as NSUserDefaults to pull out the raw value automatically.

So now I'm more likely to follow this more obvious rule of thumb: if this is just a glorified namespace for some constants, a struct with static members seems simplest. An enum is for a switch, i.e. something that needs to exist in exactly one of several possible states.

But I don't even follow that rule consistently, because the enum with the raw value has advantages that the struct does not. For example, if you have an enum with a raw value, then you can get from the raw value to the corresponding enum case really easily (by calling init(rawValue:)). That's not so easy with a struct.

like image 111
matt Avatar answered Oct 06 '22 01:10

matt