舉例說明我想實現的,比如我有十個變量(整數值)以及變量的值,一個字符串。
然後代碼中是判斷雲的數量決定天氣狀況:
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的值,能不能對所有組都變成通用方法?
方法如下:
- (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];