[英]Iphone — maintaining a list of strings and a corresponding typedef enum
假設我有以下內容:
typedef enum functionType {ln, sin, sqrt} functionType;
NSArray *functions = [NSArray arrayWithObjects: @"ln", @"sin", @"sqrt", nil];
進一步假設*功能在運行時不會改變。
問題-有沒有辦法建立一個可以更新這兩個結構的單一結構? 這樣我只需要跟蹤一個列表,而不是兩個即可。
為了解釋正在發生的事情-想法是,來自用戶的字符串輸入將存儲在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需要快速。 所以我不想在那里進行字符串比較。
聽起來您想要一個從字符串到枚舉對象的映射。 有很多方法可以做到這一點。
您可以使用帶有NSString鍵和代表對象的NSNumber編碼整數的NSDictionary。
您可以使用函數名稱(@“ ln”,@“ sin”等)的NSArray,並且僅將索引存儲到數組中; 這基本上擺脫了枚舉。
如果您確實想要枚舉類型和字符串對象的聯接列表,則還可以執行以下操作:
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"},
};
但是要當心符號沖突! 您不能有一個名為sin的枚舉標識符,也不能使用標准的sin()函數。
祝您計算器型應用程序好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.