Elstine P
Elstine P

Reputation: 370

how do we do enum constructor in objective c

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;
    }
}

Source

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 ?

Upvotes: 0

Views: 284

Answers (1)

CRD
CRD

Reputation: 53010

(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 int type though this can be changed to other integral types, which can be used more-or-less interchangeably as an int (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:

typedef enum
{
   HAMBURGER = 7,
   FRIES = 2,
   HOTDOG = 3,
   ARTICHOKE = 4
} Food;

This gives you a type, Food, with four literal values, HAMBURGER et al; and assignment, equality, switch statements etc. all work as expected. E.g.:

Food item = HOTDOG;
if (item == FRIES) ...
switch (item) { case ARTICHOKE: ...

You can also use the literals as integers to get the "price", e.g.

int itemPrice = (int)item;

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 own class/struct and methods/functions to implement the functionality you require.

HTH

Upvotes: 3

Related Questions