Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enum as a type?

Say inside of a class Card, you have declared

typedef enum {
  CLUBS, DIAMONDS, HEARTS, SPADES
} Suit

and a

typedef enum {
  SIX, SEVEN, EIGHT ..
} Value

and a designated initializer

-(id) initWithValue: (Value) c andSuit: (Suit) s;

How then would you use this initializer from outside of a class?

I tried:

[Card alloc] initWithValue: (Card) Value.SIX andSuit: (Card) Suit.HEARTS];

Please assist

like image 281
James Raitsev Avatar asked Jan 29 '26 06:01

James Raitsev


2 Answers

Card *card = [[Card alloc] initWithValue: SIX andSuit: HEARTS];
like image 124
beryllium Avatar answered Jan 30 '26 19:01

beryllium


I'll give an expanded answer. Your code will be a lot more readable if you follow standard obj-c naming conventions.

Generally, you would adopt a conventional naming scheme for your enumeration using your class name followed by a relevant type name such as:

typedef enum {
    CardSuitClubs,
    CardSuitDiamonds,
    CardSuitHearts,
    CardSuitSpades
} CardSuit;

typedef enum {
    CardValueTwo,
    ...,
    CardValueAce
} CardValue;

Then, you include card.h where you need it and use your initializer as follows:

Card *card = [[Card alloc] initWithCardValue:CardValueAce andCardSuit:CardSuitSpades];
like image 32
XJones Avatar answered Jan 30 '26 20:01

XJones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!