具有静态常量的字符串类型vs struct的枚举 [英] enum of string type vs struct with static constant

查看:100
本文介绍了具有静态常量的字符串类型vs struct的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎当需要使用(字符串类型的)枚举时,也可以使用带有静态字段的struct来实现。

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

eg

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

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?

推荐答案

它们都是完全可行的。

我以前认为枚举方法不太灵活,因为您必须明确询问$原始值,以便到达基础字符串,但我不再这么认为,因为有一些方法可以扩展诸如NSUserDefaults之类的类,以自动 提取原始值。

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.

所以我现在更多很有可能遵循以下明显的经验法则:如果这只是某些常量的美化命名空间,则具有静态成员的结构似乎最简单。枚举是用于 switch 的,即某种东西必须确切地存在于几种可能的状态中。

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.

但我什至不关注该规则始终如一,因为带有原始值的枚举具有结构所没有的优点。例如,如果您有一个带有原始值的枚举,则可以非常容易地从原始值获取对应的枚举大小写(通过调用 init(rawValue:)) 。使用结构并不容易。

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.

这篇关于具有静态常量的字符串类型vs struct的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆