Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between static enum and static struct

Tags:

swift

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() {}
}
like image 301
Shadow Of Avatar asked Aug 18 '16 15:08

Shadow Of


People also ask

Can enum be static in Swift?

Swift's Enum can add a Static Method. You can use this to create methods that return the UI expression values ​​of all enumeration items as an array. It is the final version of the Married Enum type. Static method called strings is added to return all possible expression values as an array.

What is the difference between struct vs enum Swift?

Coming from an objective c background, the difference between components like enums, classes, and structs was quite obvious for me: An Enum is a set of named values, Struct is structured data type, and of course Class allows us to create objects with all POO related stuff.

Can enum be static C++?

static cannot be applied to enum declarations, so your code is invalid.

Is enum static C#?

Hi, enum can not be static. enum is a type and can be defined independently or inside a class (which is also a type).


1 Answers

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
like image 139
Hamish Avatar answered Sep 17 '22 17:09

Hamish