Swift 常量:结构或枚举 [英] Swift constants: Struct or Enum
问题描述
我不确定两者中的哪一个更适合定义常量.一个结构体或一个枚举.每次我使用它时都会复制一个结构吗?在我看来,当我想到一个带有 static let
常量的结构时,它会一直复制是没有意义的.但如果它不会被复制,那么我拿什么都无所谓?
I'm not sure which of both are better to define constants. A struct or a enum. A struct will be copied every time i use it or not? When i think about a struct with static let
constants it makes no sense that it will copied all the time, in my opinion. But if it won't copied then it doesn't matter what I take?
选择结构体或枚举有什么好处?
What advantages does the choice of a struct or enum?
Ray Wenderlich 说使用 Enum 的.但我缺乏理由.
推荐答案
结构和枚举都有效.例如,两者
Both structs and enumerations work. As an example, both
struct PhysicalConstants {
static let speedOfLight = 299_792_458
// ...
}
和
enum PhysicalConstants {
static let speedOfLight = 299_792_458
// ...
}
工作并定义一个静态属性PhysicalConstants.speedOfLight
.
work and define a static property PhysicalConstants.speedOfLight
.
struct
和 enum
都是值类型,因此也适用于枚举.但这在这里无关因为你根本不需要创造价值:静态属性(也称为 type 属性)是类型本身的属性,而不是该类型的实例的属性.
Both struct
and enum
are value types so that would apply to enumerations as well. But that is irrelevant here
because you don't have to create a value at all:
Static properties (also called type properties) are properties of the type itself, not of an instance of that type.
如链接文章中所述:
使用无大小写枚举的优点是它不会被意外实例化并且可以作为纯命名空间使用.
The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace.
所以对于结构,
let foo = PhysicalConstants()
创建一个 PhysicalConstants
类型的(无用的)值,但是对于无大小写的枚举,它无法编译:
creates a (useless) value of type PhysicalConstants
, but
for a case-less enumeration it fails to compile:
let foo = PhysicalConstants()
// error: 'PhysicalConstants' cannot be constructed because it has no accessible initializers
这篇关于Swift 常量:结构或枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!