1

Sample code:

enum BestLetters {
    case A
    case B
    case C
    case Default = B
}

The error in the Default case: Raw value for enum case must be a literal

My understanding is that enum raw values are limited to certain types (Ints, Strings, Booleans, etc). Obviously BestLetters isn't one of those types and the compiler is complaining.

How can I set the Default type's raw value to one of the other "letters"? If gives any context, the reason for this odd syntax is that I am trying to imitate something I saw in obj-c.

Thank you for your help.

GranolaGuy
  • 133
  • 12
  • 3
    How will this be used? Might help to show the Objective-C code. Also add an example of how you want to use this default. – rmaddy Dec 05 '18 at 20:27

1 Answers1

3

In (Objective-)C an enumeration defines a set of named integer constants, and those need not be distinct:

enum {
    A = 1,
    B = 2,
    C = 99,
    Default = B
};

The cases of a Swift enum represent mutually distinct values, and their raw values – if assigned – must be unique:

enum BestLetters: Int {
    case a = 1
    case b
    case c
    case `default` = 2 // Error: Raw value for enum case is not unique
}

On the other hand, enumerations in Swift are first-class types, so that you can define a static property for that purpose:

enum BestLetters {
    case a
    case b
    case c
    static let `default` = BestLetters.b
}

(This is also how Swift imports C enumerations with duplicate values, compare touchIDLockout deprecated in iOS 11.0.)

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thank you! Why the backticks around default? – GranolaGuy Dec 06 '18 at 14:00
  • 1
    @GranolaGuy: Because “default” is a reserved word in Swift, compare e.g. https://stackoverflow.com/q/41503740/1187415. If you rename it to “defaultLetter” then the backticks are not needed. – Martin R Dec 06 '18 at 14:10
  • This is a good read on enum inits [1]: https://www.objc.io/blog/2018/03/13/mutable-self/ – user6902806 Dec 21 '18 at 12:06