程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> ios-怎麼樣讓不同變量重復一個動作?

ios-怎麼樣讓不同變量重復一個動作?

編輯:編程綜合問答
怎麼樣讓不同變量重復一個動作?

舉例說明我想實現的,比如我有十個變量(整數值)以及變量的值,一個字符串。

然後代碼中是判斷雲的數量決定天氣狀況:

 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];
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved