tags:

views:

233

answers:

1

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.

+1  A: 

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!

Tyler
Just to comment -- what you are saying is that there is no way to do what I really want, which is to have some type of automatic correspondence between the enum name and the NSString objects. I have to track them myself. That said, +1 and accepted because you are offering me the best existing alternatives.
William Jockusch