Shadow Of Shadow Of - 3 months ago 7
Swift Question

Difference between static enum and static struct

Let say that enum or struct are static if they don't store any values in instances. Is there is any difference between static enum and static struct?

enum StaticEnum {
static var someStaticVar = 0
static func someStaticFunc() {}
}

struct StaticStruct {
static var someStaticVar = 0
static func someStaticFunc() {}
}

Answer

The main difference is that you cannot construct an enum with no cases. Therefore if you're just looking for something to serve as a namespace for some static members, an enum is preferred as you cannot accidently create an instance.

let e = StaticEnum() // error: 'StaticEnum' cannot be constructed because it has no accessible initializers
let s = StaticStruct() // Useless, but legal