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?
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.
So it is not possible to have a certain Enum extend and inherit the cases of another enum.
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.
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.
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
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