简体   繁体   English

在枚举中使用静态 let 而不是 case

[英]Using static let in enum instead of case

I have noticed certain cases where inside an enum, instead of case people have used static let to declare variables.我注意到某些情况在枚举内部,而不是人们使用 static let 来声明变量的情况。 Is this practice justifiable?这种做法合理吗?

public enum ExampleEnum {
    static let case1 = "case1"
    static let case2 = "case2"
    static let case3 = "case3"
}

This is a quick way of creating a namespace for constants.这是为常量创建命名空间的快速方法。

You can of course achieve similar effect using a struct, however running let foo = StructOnlyForStoringConstants() will not throw an error or even a warning (can be solved using private init or even logging a warning, but we quickly lose the quick in a quick way above) and hence might be confusing ( some argue ).您可以使用一个结构,但是在运行的过程中实现类似的效果let foo = StructOnlyForStoringConstants()不会引发错误,甚至警告(可以使用来解决private init ,甚至记录警告,但我们很快就失去了quicka quick way上面的a quick way ),因此可能会令人困惑(有些人争论)。 Since enums without cases (or " no-case enums ") cannot be instantiated, you don't have this problem.由于没有案例的枚举(或“ no-case enums ”)无法实例化,因此您没有这个问题。

Another reason is that putting constants in an enum might feel more natural (than say in structs), as enums are used for storing a group of related values.另一个原因是将常量放在枚举中可能感觉更自然(比在结构中说),因为枚举用于存储一组相关值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM