19

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() {}
}
Yury
  • 6,044
  • 3
  • 19
  • 41

1 Answers1

22

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
Hamish
  • 78,605
  • 19
  • 187
  • 280
  • 2
    Using `enum` as a way of name spacing seems odd. I found it pretty unclear at first. But I'm not sure it's worth having a seperate `namespace` construct that acts essentially like a case-less `enum` – Alexander Aug 18 '16 at 15:58
  • @AlexanderMomchliov I certainly agree that it feels a bit weird using a case-less enumeration as a namespace, it feels like more like a useful side-effect than an intended feature. Although given how infrequently 'just a namespace' is actually needed (I can only think of one example in the stdlib, [`MemoryLayout`](https://developer.apple.com/reference/swift/memorylayout), but even that takes advantage of a generic parameter so isn't quite 'just a namespace'), I can understand the lack of a `namespace` construct. – Hamish Aug 18 '16 at 16:10