Can you inherit enum in Swift? What are the rules that one should be aware of with regards to enum inheritance?
The following test code:
enum TemperatureUnit: Int { case Kelvin, Celcius, Farenheit } enum TemperatureSubunit : Temperature { }
generates
error: type 'TemperatureSubunit' does not conform to protocol 'RawRepresentable'
In Swift language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.
Enums cannot inherit from other enums. In fact all enums must actually inherit from System. Enum . C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.
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.
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 language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.
So to answer your question, you can't have inheritance with Enum (and Struct types). Have a look here:
stackOverflow difference classes vs structs
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