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"
We can extend the enum in two orthogonal directions: we can add new methods (or computed properties), or we can add new cases. Adding new methods won't break existing code. Adding a new case, however, will break any switch statement that doesn't have a default case.
The name of an enum in Swift should follow the PascalCase naming convention in which the first letter of each word in a compound word is capitalized.
Yes, enums can conform protocols. You can use Swift's own protocols or custom protocols. By using protocols with Enums you can add more capabilities.
In Swift, we can also assign values to each enum case. For example, enum Size : Int { case small = 10 case medium = 12 ... } Here, we have assigned values 29 and 31 to enum cases small and medium respectively.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With