Swift常数:Struct或Enum [英] Swift constants: Struct or Enum

查看:137
本文介绍了Swift常数:Struct或Enum的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道哪一个更好地定义常量。一个结构体或枚举。每次使用结构都会被复制?当我想到一个具有 static的结构时,这个常量在任何时候都不会被复制,在我看来。但是如果不会复制,那么我所需要的不重要?

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?

Francisco表示使用Struct's。

Ray Wunderlich说使用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

struct 枚举是值类型,因此也适用于枚举。但是这是$ / $> $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $的类型本身,而不是这种类型的实例。

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常数:Struct或Enum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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