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.
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 .)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.