Iphone——维护字符串列表和相应的 typedef 枚举
假设我有以下内容:
typedef enum functionType {ln, sin, sqrt} functionType;
NSArray *functions = [NSArray arrayWithObjects: @"ln", @"sin", @"sqrt", nil];
进一步假设 *functions 在运行时不会改变。
问题——有没有办法建立一个单一的结构来更新这两者?这样我只需跟踪一个列表,而不是两个。
为了解释发生了什么——这个想法是用户输入的字符串将存储在 functionType 类型的变量中。稍后,我将有这样的代码:
double valueOfFunction: (functionType) function withInput: (double) input
switch (function) {
case ln:
return ln(input);
case sin:
return sin(input);
case sqrt:
return sqrt(input);
//etc . . . could grow to include a lot of functions.
}
并且 valueOfFunction 需要很快。所以我不想在那里进行字符串比较。
Suppose I have the following:
typedef enum functionType {ln, sin, sqrt} functionType;
NSArray *functions = [NSArray arrayWithObjects: @"ln", @"sin", @"sqrt", nil];
Suppose further that *functions will not change at runtime.
Question -- is there any way to set up a single structure which updates both of these? So that I only have to keep track of one list, instead of two.
To explain what is going on -- the idea is that string input from the user will be stored in a variable of type functionType. Later on, I will have code like this:
double valueOfFunction: (functionType) function withInput: (double) input
switch (function) {
case ln:
return ln(input);
case sin:
return sin(input);
case sqrt:
return sqrt(input);
//etc . . . could grow to include a lot of functions.
}
And valueOfFunction needs to be fast. So I don't want to be doing string comparisons there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您想要一个从字符串到枚举对象的映射。有多种方法可以做到这一点。
您可以使用带有 NSString 键和表示对象的 NSNumber 编码整数的 NSDictionary。
您可以使用函数名称(@“ln”,@“sin”等)的 NSArray,并且仅将索引存储到数组中;这基本上摆脱了枚举。
如果您确实想要一个枚举类型和字符串对象的连接列表,您也可以执行以下操作:
不过,请注意符号冲突!您不能在拥有名为 sin 的枚举标识符的同时还使用标准 sin() 函数。
祝您的计算器类型应用程序好运!
It sounds like you want a map from strings to enum objects. There are a number of ways to do this.
You could use an NSDictionary with NSString keys and NSNumber-encoded ints representing the objects.
You could use an NSArray of the function names (@"ln", @"sin", etc), and only store the index into the array; this basically gets rid of the enum.
If you really want a joined list of enum types and string objects, you could also do something like this:
Watch out for symbol clashes, though! You can't have an enum identifier called sin and also use the standard sin() function.
Good luck with your calculator-type app!