gpt4 book ai didi

Swift 常量 : Struct or Enum

转载 作者:IT王子 更新时间:2023-10-29 04:58:02 25 4
gpt4 key购买 nike

我不确定两者中哪一个更适合定义常量。结构或枚举。每次我使用或不使用时都会复制一个结构?在我看来,当我想到一个带有 static let 常量的结构时,它会一直复制是没有意义的。但如果它不会被复制,那么我拿什么都没关系?

选择结构或枚举有什么优势?

Francescu says use structs.

Ray Wenderlich says use enums. But I lack the justification.

最佳答案

结构和枚举都有效。例如,两者

struct PhysicalConstants {
static let speedOfLight = 299_792_458
// ...
}

enum PhysicalConstants {
static let speedOfLight = 299_792_458
// ...
}

工作并定义一个静态属性PhysicalConstants.speedOfLight

Re: 无论我是否使用一个结构体,它都会被复制吗?

structenum 都是值类型,因此也适用于枚举。但这在这里无关紧要因为你根本不需要创造值(value):静态属性(也称为类型 属性)是类型本身的属性,而不是该类型实例的属性。

回复:选择结构体或枚举有什么优势?

linked-to article 中所述:

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 的(无用的)值,但是对于无大小写的枚举,它无法编译:

let foo = PhysicalConstants()
// error: 'PhysicalConstants' cannot be constructed because it has no accessible initializers

关于Swift 常量 : Struct or Enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38585344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com