Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift enum inheritance

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' 
like image 537
Boon Avatar asked Oct 17 '15 21:10

Boon


People also ask

Can enum inherit in Swift?

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.

Can enums have inheritance?

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.

Can enum be extended in Swift?

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.

Can enum conform to Swift protocol?

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.


1 Answers

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

like image 165
Korpel Avatar answered Sep 19 '22 12:09

Korpel