Hi, there~
What can i do for this below? I wanna to expand case options. Any solutions?
Thx for ur attention.
Hi, there~
What can i do for this below? I wanna to expand case options. Any solutions?
You cannot add extra cases to an enum
. A common way to resolve this is to declare Environment
[1] as a struct
and then declare each case as a static property:
struct Environment: RawRepresentable {
var rawValue: String
static let dev = Environment(rawValue: "dev")
static let qa = Environment(rawValue: "qa")
static let pro = Environment(rawValue: "pro")
}
extension Environment {
static let live = Environment(rawValue: "live")
}
You are, of course, responsible for making sure that the raw values don’t collide.
ps It’d help if you posted your code as text rather than a screen shot. That way folks can copy’n’paste it. In Markdown you can use triple backticks to denote a code block.
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple
[1] I’m going to use Swift standard style for identifiers. Environment
, being a type, should start with a capital.
Hey, eskimo
Thank you for your detail answers.
I will try what you recommend.
Thank you again.
Such a great answer, thank you so much!
Out of curiosity: is there a reason why enums cannot be extended?
Enums can be extended through protocols and extensions, but you cannot add new enum cases through extensions.
The reason behind this is because it would break the single source of truth that the enum
is based on, which would make maintaining a code base impossible because you would no longer have control over how your code behaves.
Now multiply that with all the libraries available today that use enums. If you added a new enum case to a dependency through an extension, that dependency and all the dependencies relying on it would not compile because they do not handle the new case.