objective-c - 使用枚举将类型分配给一系列整数?

标签 objective-c c enums

我有一个索引数组 [1 ... 20]。 indexArray 的前 4 个元素链接到某种类型的文件(称为类型 A),其他 16 个元素链接到类型 B。

我随机打乱数组。我现在希望提取 4 个索引,但 4 个索引中最多只有一个可以是 A 类型。

我想我需要在这里使用枚举函数将索引 1-4 定义为“类型 A”,将索引 5-20 定义为“类型 B”,那么如果我查看例如我新随机化的indexArray[0]的第一个元素我可以知道它是什么类型并采取相应的行动。

我从示例中看到枚举的使用方式如下:

enum category { typeA = 0, typeB };

是否可以将索引 1-4 分配给 typeA,其余分配给 typeB,还是我在这里走错了路?提前致谢。

编辑以包含代码片段

我尝试对此进行测试并立即遇到错误

 #import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

int* indices = malloc(20*sizeof(int));

for (int i=0; i<20; i++) {

    indices[i] = i;

}

enum category {typeA, typeB};


enum category categoryForIndex(int index) {
    if (index >= 1 && index <= 4) {
        return typeA;
    } else {
        return typeB;
    }
}

[pool drain];
return 0;

}

当我尝试编译这个时,我收到错误“嵌套函数被禁用,使用 -fnested-functions 重新启用”,这通常发生在第二个主函数意外地被放入混合中或类似的情况时。有任何想法吗?

编辑以包含一些代码,展示如何将解决方案付诸实践

#import <Foundation/Foundation.h>

enum category {typeA, typeB};

enum category categoryForIndex(int index) {
if (index >= 1 && index <= 4) {
    return typeA;
   } else {
    return typeB;
    }

}

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

int* indices = malloc(20*sizeof(int));

for (int i=1; i<=20; i++) {

    indices[i] = i;

}


NSLog(@"index[0] is %i:", indices[16]);

enum category index;

index = indices[16];

switch (categoryForIndex(index)) {   //this tests to see what category 16 belongs to
    case typeA:
        NSLog(@"index is of type A");   
        break;
    case typeB:
        NSLog(@"index is of type B");
        break;
    default:
        NSLog(@"index not valid");
        break;
}

 [pool drain];
 return 0;

}

最佳答案

你偏离了轨道。您不能将 1-4 分配给给定的枚举。枚举常量恰好具有一个值,并且只有一个值。您可以做的是使用枚举来定义两种类型,如您已经完成的那样,例如 typeAtypeB,然后定义一个将索引映射回类型,例如

enum category categoryForIndex(int index) {
    if (index >= 1 && index <= 4) {
        return typeA;
    } else {
        return typeB;
    }
}

现在您可以对索引进行分类了。

关于objective-c - 使用枚举将类型分配给一系列整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9086284/

相关文章:

iphone - 从 iPhone 获取日志文件的最简单方法是什么?

c - += 运算符链接(带一点 UB)

c - 如何为具有 char* 成员的结构分配内存

java - 在Java中调用枚举变量

c# - 从 ExecuteMethodCall() 获取枚举

objective-c - .m 文件的引用在哪里?

ios - Objective-C 中的单元测试私有(private)类

清除 double 的尾随 0?

c - 对变量 i 的 undefined reference

java - 如何将枚举与父类(super class)型分组