Search code examples
objective-cvariablescallclutter

Simple clutter-free way to call multiple variables


I'm looking to do something like

int ItemNames;
typedef enum ItemNames {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?


Solution

  • 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.