Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum multiple cases with the same value in Swift

Tags:

enums

swift

In C you could make your enums have this:

typedef enum _Bar {     A = 0,     B = 0,     C = 1 } Bar; 

In Swift I want to make the equivalent. However, the compiler complains that it isn't unique. How do I tell it that I want two cases to have the same value?

enum Bar : Int {     case A = 0     case B = 0 // Does not work     case C = 1 } 

I've tried

case A | B = 0 

and

case A, B = 0 

But it doesn't seem to work as I want it to.

like image 806
DerrickHo328 Avatar asked Jan 20 '15 04:01

DerrickHo328


People also ask

Can multiple enum have same value?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

What is associated value in enum Swift?

In Swift enum, we learned how to define a data type that has a fixed set of related values. However, sometimes we may want to attach additional information to enum values. These additional information attached to enum values are called associated values.

What is difference between enum and enumeration in Swift?

Enumeration is a data type that allows you to define a list of possible values. An enum allows you to create a data type with those set of values so that they can be recognised consistently throughout your app.

Can enum conform to Swift protocol?

Yes, enums can conform protocols. You can use Swift's own protocols or custom protocols. By using protocols with Enums you can add more capabilities.


1 Answers

Swift doesn't support duplicated values (or "aliases" semantically). If you don't mind, you can mimic it by using something like this:

enum Foo: Int {     case Bar = 0      static var Baz:Foo {         get {             return    Bar         }     }     static var Jar:Foo {         get {             return    Foo(rawValue: 0)!         }     } } 

With recent version of Swift, this can be shortened like this:

enum Foo: Int {     case bar = 0      static var baz:Foo { .bar }     static var jar:Foo { Foo(rawValue: 0)! } } 

Note that Swift has changed their naming convention of enum variants from PascalCase to camelCase.

like image 83
eonil Avatar answered Sep 29 '22 21:09

eonil