Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift enum cases with same name [duplicate]

Tags:

swift

Let's say I have the following enum:

enum Measurement {
 case Volume(litre: Double)
 case Volume(millilitre: Double)
 case Length(cm: Double)
}

Then when I do a switch statement like so:

switch measurement {
 case .Volume(let val):
...   

How can I differentiate between the two Volume cases? Or is this really impossible, and I should have VolumeLitre & VolumeMillilitre instead?

like image 377
Anton Gregersen Avatar asked Apr 04 '19 11:04

Anton Gregersen


People also ask

Can Swift enumerations nested?

To accomplish this, Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support. To nest a type within another type, write its definition within the outer braces of the type it supports.

Can enum extend another enum Swift?

So it is not possible to have a certain Enum extend and inherit the cases of another enum.

Can Swift enums have methods?

Swift's Enum can have methods. It can have instance methods and you can use it to return expression value for the UI. Let's look at the code above.

Can enum adopt protocol Swift?

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

You could create another enum that represent the volume:

enum Volume {
    case litre(Double)
    case millilitre(Double)
}

enum Measurement {
    case volume(Volume)
    case length(cm: Double)
} 

Also, for enum cases, use lowercase

like image 195
Rico Crescenzio Avatar answered Oct 06 '22 06:10

Rico Crescenzio