我不确定如何解释这一点,但我很肯定有办法做到这一点,但我还没有得到它。这是我的例子:我有10个变量(整数值),并且使用变量的值,设置一个字符串。
以下是天气和云层的示例,以确定天气状况:
if (hour1cloud <= 5) {
hour1weather = @"Clear";
}
if (5 < hour1cloud <= 25) {
hour1weather = @"Mostly Clear";
}
if (25 < hour1cloud <= 50) {
hour1weather = @"Partly Cloudy";
}
if (50 < hour1cloud <= 83) {
hour1weather = @"Mostly Cloudy";
}
if (83 < hour1cloud <= 105) {
hour1weather = @"Overcast";
}
假设我有hour2cloud,hour3cloud,hour4cloud等,它们与hour2weather,hour3weather等相反。有没有办法我可以制作一个通用方法,我只需输入hour1cloud并检索hour1weather?
答案 0 :(得分:2)
你当然可以这样做:
static NSString *stringForCloudiness(int cloudiness) {
static int const kCloudinesses[] = { 5, 25, 50, 83, 105 };
static NSString *const kStrings[] = { @"Clear", @"Mostly Clear", @"Partly Cloudy", @"Mostly Cloudy", @"Overcast" };
static int const kCount = sizeof kCloudinesses / sizeof *kCloudinesses;
for (int i = 0; i < kCount; ++i) {
if (cloudiness <= kCloudinesses[i]) {
return kStrings[i];
}
}
return @"A cloudiness level unparalleled in the history of recorded weather";
}
这有点复杂但确保您不要忘记保持阵列同步:
static NSString *stringForCloudiness(int cloudiness) {
typedef struct {
int cloudiness;
__unsafe_unretained NSString *string;
} CloudStringAssociation;
static CloudStringAssociation const kAssociations[] = {
{ 5, @"Clear" },
{ 25, @"Mostly Clear" },
{ 50, @"Partly Cloudy" },
{ 83, @"Mostly Cloudy" },
{ 105, @"Overcast" },
{ INT_MAX, @"A cloudiness level unparalleled in the history of recorded weather" }
};
int i = 0;
while (cloudiness > kAssociations[i].cloudiness) {
++i;
}
return kAssociations[i].string;
}
答案 1 :(得分:1)
为什么不写这样的方法:
- (NSString*)weatherStringFromCloud:(int)cloud {
NSString *weather;
if (cloud <= 5) {
weather = @"Clear";
} else if (cloud <= 25) {
weather = @"Mostly Clear";
} else if (cloud <= 50) {
weather = @"Partly Cloudy";
} else if (cloud <= 83) {
weather = @"Mostly Cloudy";
} else if (cloud <= 105) {
weather = @"Overcast";
} else {
weather = nil;
}
return weather;
}
然后使用各种值调用它:
hour1weather = [self weatherStringFromCloud:hour1cloud];
hour2weather = [self weatherStringFromCloud:hour2cloud];
hour3weather = [self weatherStringFromCloud:hour3cloud];
hour4weather = [self weatherStringFromCloud:hour4cloud];