James Raitsev
James Raitsev

Reputation: 96391

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

Upvotes: 2

Views: 578

Answers (3)

XJones
XJones

Reputation: 21967

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

Upvotes: 5

beryllium
beryllium

Reputation: 29767

Card *card = [[Card alloc] initWithValue: SIX andSuit: HEARTS];

Upvotes: 6

rob mayoff
rob mayoff

Reputation: 385600

Just this:

[[Card alloc] initWithValue:SIX andSuit:HEARTS];

Upvotes: 1

Related Questions