开发者

Simple clutter-free way to call multiple variables

I'm looking to do something like

int ItemNames;
typedef enum ItemNam开发者_开发技巧es {apple, club, vial} ItemNames;    
+(BOOL)GetInventoryItems{return ItemNames;}
apple=1; //Compiler Error.

The issue is, is that I cannot set a variable in an enum to a new value. The compiler tells me that I have "redeclared" an integer in the enum. Also, it won't correctly return the values. So instead I have to use an if statement for each item to check if it exists like so.

+ (void)GetInventoryItems
{
    if (apple <= 1){NSLog(@"Player has apple");}
    if (club <= 1){ NSLog(@"Player has club");}
    if (vial <= 1){NSLog(@"Player has vial");}
    if (apple == 0 && club == 0 && vial == 0){NSLog(@"Player's Inventory is Empty.");}
}

Is there a work around?


You're trying to use the wrong data structure. An enum is just a list of possible values, a data type and not a variable.

typedef struct {
  int apple : 1;
  int club : 1;
  int vial : 1;
}
inventory_type;

inventory_type room;

room.apple = 1;

if (room.apple) NSLog (@"There's an apple");
if (room.club) NSLg (@"There's a club!");

The colon and number after each element of the typedef tells the compiler how many bits to use, so in this case a single bit (i.e., a binary value) is available.


The enum values are constants, so they can't be modified. Objective-c is a c-based language, so ItemNames isn't an object, it is a type.


I find it hard to wrap my head around your question. Are you sure you know how enum works in C? It’s just a way to conveniently declare numeric constants. For example:

enum { Foo, Bar, Baz };

Is something like:

static const NSUInteger Foo = 0;
static const NSUInteger Bar = 1;
static const NSUInteger Baz = 2;

If you want to pack several inventory items into a single value, you might use a bit string:

enum {
    Apple  = 1 << 1,
    Banana = 1 << 2,
    Orange = 1 << 3
};

NSUInteger inventory = 0;

BOOL hasApple  = (inventory & Apple);
BOOL hasBanana = (inventory & Banana);

inventory = inventory | Apple; // adds an Apple into the inventory

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜