1

我想做类似的事情

int ItemNames;
typedef enum ItemNames {apple, club, vial} ItemNames;    
+(BOOL)GetInventoryItems{return ItemNames;}
apple=1; //Compiler Error.

问题是,我无法将枚举中的变量设置为新值。编译器告诉我我在枚举中“重新声明”了一个整数。此外,它不会正确返回值。因此,我必须对每个项目使用 if 语句来检查它是否存在。

+ (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.");}
}

有解决办法吗?

4

3 回答 3

3

您正在尝试使用错误的数据结构。枚举只是可能值的列表、数据类型而不是变量。

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!");

typedef 的每个元素后面的冒号和数字告诉编译器要使用多少位,因此在这种情况下,单个位(即二进制值)可用。

于 2011-05-18T15:14:42.867 回答
1

枚举值是常量,因此无法修改。Objective-c 是一种基于 c 的语言,所以 ItemNames 不是一个对象,它是一种类型。

于 2011-05-18T15:08:28.707 回答
1

我发现很难回答你的问题。你确定你知道enum在 C 中是如何工作的吗?这只是一种方便地声明数字常量的方法。例如:

enum { Foo, Bar, Baz };

是这样的:

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

如果你想将几个库存项目打包成一个值,你可以使用一个位字符串:

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

希望这可以帮助。

于 2011-05-18T15:14:15.877 回答