如果以更好的方式检查其他代码,我怎么能写这个呢? [英] How could I write this if else code checking in a better way?
本文介绍了如果以更好的方式检查其他代码,我怎么能写这个呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果是其他代码检查,这是写这个的最好方法吗?
Is this the best way to write this if else code checking?
// set the default to Italy if countrySaved is null
if (lang == NULL) {
lang = @"it";
}
// otherwise set the correct lang based on the country chosed and saved in nsuserdefaults
if ([countrySaved isEqual:@"Brazil"]) {
lang = @"br";
}
else if ([countrySaved isEqual:@"Spain"]) {
lang = @"es";
}
else if ([countrySaved isEqual:@"Italy"]) {
lang = @"it";
}
else if ([countrySaved isEqual:@"United States"]) {
lang = @"us";
}
else if ([countrySaved isEqual:@"United Kingdom"]) {
lang = @"uk";
}
感谢您的帮助
推荐答案
将语言ID存储在字典中:
Store the language IDs in a dictionary:
NSDictionary *languageIDs = @{
@"Brazil" : @"br",
@"Spain" : @"es",
@"Italy" : @"it",
@"United States" : @"us",
@"United Kingdom" : @"uk"
};
然后只需从字典中分配 lang
:
Then simply assign lang
from said dictionary:
lang = languageIDs[countrySaved];
if (!lang) {
lang = languageIDs[@"Italy"];
}
或者我用三元运算符做的更短的方式:
Or the shorter way I'd do it using a ternary operator:
lang = languageIDs[countrySaved] ?: languageIDs[@"Italy"];
你也应该从plist加载它们文件或使用 NSString consts
,以避免最终多余的文件和遍布代码的不可维护的文字。
Also you should probably either load them from a plist file or use NSString consts
in order to avoid eventually redundant and by that unmaintainable literals scattered all over your code.
这篇关于如果以更好的方式检查其他代码,我怎么能写这个呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文