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.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With