SnowN SnowN - 1 year ago 74
Swift Question

Swift constants: Struct or Enum

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 say use Struct's.

Ray Wunderlich say use Enum's. But I lack the justification.

Answer Source


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


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

work and define a static property PhysicalConstants.speedOfLight.

A struct will be copied every time i use it or not?

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.

As mentioned in the 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.

So for a structure,

let foo = 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