开发者

Iphone -- maintaining a list of strings and a corresponding typedef enum

开发者 https://www.devze.com 2022-12-25 02:31 出处:网络
Suppose I have the following: typedef enum functionType {ln, sin, sqrt} functionType; NSArray *functions = [NSArray arrayWithObjects: @\"ln\", @\"sin\", @\"sqrt\", nil];

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 valu开发者_JAVA百科eOfFunction needs to be fast. So I don't want to be doing string comparisons there.


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:

typedef enum FunctionType {
  ln, sin, cos, tan, exp
} FunctionType;

typedef struct FunctionItem {
  FunctionType type;
  NSString *name;
} FunctionItem;

FunctionItem functions[] = {
  {ln, @"ln"},
  {sin, @"sin"},
  {cos, @"cos"},
  {tan, @"tan"},
  {exp, @"exp"},
};

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号