Enum multiple cases with the same value in Swift

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.


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

Tags:

Enums

Swift