12

I am trying to achieve the following in Swift. Adding more cases to enum rather than editing on the existing one.

For example, I have the following enum and I want to add more cases using extension, not to edit on the original enum.

enum UIType: String, Codable {
    case borderButton = "border_button"
    case bottomSheet = "bottom_sheet"
}

Now if I want to add more elements to enum

case borderLabel = "border_Label"
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Amr Angry
  • 3,711
  • 1
  • 45
  • 37
  • This link helpful for you https://stackoverflow.com/questions/34025674/adding-a-case-to-an-existing-enum-with-a-protocol][1] –  Nov 02 '18 at 07:00

2 Answers2

10

This is not possible. Adding a case to an enum in an extension would be comparable to adding a stored property for a class or struct. (This is also not possible)

See also the documentation:

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). — https://docs.swift.org/swift-book/LanguageGuide/Extensions.html

Extension can just add new functionality.

Adding properties would change the the memory size that is needed to store an object.

Fedor Pashin
  • 121
  • 1
  • 7
Ugo Arangino
  • 2,802
  • 1
  • 18
  • 19
  • Yes, it would change the memory size but how is that relevant if OP asked about extensions and these are known before runtime? – villasv Jan 19 '22 at 21:16
7

enum cases can't be added outside (like extensions/categories for classes) the enum for a good reason. For example, let's say you have an enum that only has exactly two cases. You would use it in a switch case like the following

var myEnumVar : MyEnumType = ....;
// ..... later on
switch(myEnumVar) {
   case MyEnumCase1: //....
   break;
   case MyEnumCase2: // do some other stuff
   break;
}

Now, imagine, someone just added another case outside the enum definition. Your code won't compile, and unless you know where exactly this case has been added (and in which file in order to import it), you would never find it out and hours of your time will be wasted till you figure it out.

sandpat
  • 1,478
  • 12
  • 30
Ahmed
  • 938
  • 7
  • 16