In java we can easily do the following enum
public enum Food {
HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4);
Food(int price) {
this.price = price;
}
private final int price;
public int getPrice() {
return price;
}
}
But I would like to do the same enum but as far as I read I couldn't find any way to do constructor in objective C like we do in java.
How to achieve the same in objective c ?
(Objective-)C enumerations are very basic.
They are not the type defined by a collection of literals, e.g. as in Ada or Pascal, though they might appear to be; neither are they the tagged disjoint union, e.g. as in Swift or Java.
Instead they are simply a collection of constants, usually of
inttype though this can be changed to other integral types, which can be used more-or-less interchangeably as anint(or whatever integral type the are).However, if your enumeration is just as described above then you can achieve something similar with a C style enum:
This gives you a type,
Food, with four literal values,HAMBURGERet al; and assignment, equality,switchstatements etc. all work as expected. E.g.:You can also use the literals as integers to get the "price", e.g.
Multiple literals can be given the same value in the underlying type, so you can have different items with the same price.
Given this you might be able to achieve something similar to your Java code without any coding beyond declaring the
enum. However if you are using the full capabilities of Java enumerations you will have to define your ownclass/structand methods/functions to implement the functionality you require.HTH