Yury
Yury

Reputation: 6114

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() {}
}

Upvotes: 20

Views: 12650

Answers (1)

Hamish
Hamish

Reputation: 80931

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

Upvotes: 22

Related Questions