Home » Swift » Swift enum multiple cases with the same value

Swift enum multiple cases with the same value

Posted by: admin November 30, 2017 Leave a comment

Questions:

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
}

Ive tried

case A | B = 0

and

case A, B = 0

But it doesn’t seem to work as I want it to. I appreciate any help.

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)!
        }
    }
}

Questions:
Answers:

Swift doesn’t allow elements of an enumto share values. From the documentation on enums under the “Raw Values” heading (emphasis mine):

Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration.

Questions:
Answers:

I’m not sure you can. The following is taken from Apple.

“Unlike C and Objective-C, Swift enumeration members are not assigned a default integer value when they are created. In the CompassPoints example above, North, South, East and West do not implicitly equal 0, 1, 2 and 3. Instead, the different enumeration members are fully-fledged values in their own right, with an explicitly-defined type of CompassPoint.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11

Since the enumeration members do not implicitly equal 0, 1, etc. the compiler looks at each as a unique value. When you try and duplicate it the compiler complains because it has already been created.

Is there are reason you need the value to be duplicated?

Questions:
Answers:

Here is another way of getting around it:

enum Animal {

  case dog
  case cat
  case mouse
  case zebra

  var description: String {
    switch self {
    case .dog:
      return "dog"

    case .cat:
      return "dog"

    case .mouse:
      return "dog"

    case .zebra:
      return "zebra"

    default:
      break
    }
  }
}