enum of string type vs struct with static constant

2019-06-26 11:41发布

问题:

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?

回答1:

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.



回答2:

I would say the main advantage of using enum over static constants is that you get compiler warnings if your switch statements are not exhaustive, hence less bugs.