开发者社区 问答 正文

如何让不同变量重复一个动作?

ios

iphone

举例说明我想实现的,比如我有十个变量(整数值)以及变量的值,一个字符串。

然后代码中是判断云的数量决定天气状况:

 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的值,能不能对所有组都变成通用方法?

展开
收起
爵霸 2016-05-27 11:42:43 1882 分享 版权
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];
    2019-07-17 19:17:35
    赞同 展开评论
问答分类:
问答地址: