调用多个变量的简单而整洁的方式
我想做类似的事情
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.");}
}
有解决办法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您试图使用错误的数据结构。枚举只是可能值的列表,是一种数据类型,而不是变量。
typedef 每个元素后面的冒号和数字告诉编译器要使用多少位,因此在这种情况下,可以使用单个位(即二进制值)。
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.
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.
枚举值是常量,因此无法修改。 Objective-c 是一种基于 C 的语言,因此 ItemNames 不是一个对象,而是一种类型。
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.
我发现很难理解你的问题。您确定知道
enum
在 C 中如何工作吗?这只是一种方便地声明数字常量的方法。例如:是这样的:
如果您想将多个库存项目打包到一个值中,您可以使用一个位字符串:
希望这会有所帮助。
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:Is something like:
If you want to pack several inventory items into a single value, you might use a bit string:
Hope this helps.