结构和枚举均起作用。例如,两者
struct PhysicalConstants { static let speedOfLight = 299_792_458 // ...}和
enum PhysicalConstants { static let speedOfLight = 299_792_458 // ...}工作并定义静态属性
PhysicalConstants.speedOfLight。
回复:每次我使用与否,都会复制一个结构吗?
这两个
struct和
enum是值类型,以便将适用于枚举为好。但这 无关紧要 ,因为您根本不必创建值:静态属性(也称为 类型
属性)是类型本身的属性,而不是该类型的实例。
回复:选择结构或枚举有什么优势?
如链接文章所述:
使用不区分大小写的枚举的优点是它不会被意外实例化并且可以用作纯名称空间。
所以对于一个结构,
let foo = PhysicalConstants()
创建一个类型的(无用)值
PhysicalConstants,但是对于一个不区分大小写的枚举,它将无法编译:
let foo = PhysicalConstants()// error: 'PhysicalConstants' cannot be constructed because it has no accessible initializers



