0

これをどう説明すればよいのか正確にはわかりませんが、これを行う方法があると確信していますが、まだ理解していません。これが私の例です: 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";
        }

hour2weather、hour3weather などに対応する hour2cloud、hour3cloud、hour4cloud などがあるとします。hour1cloud を入力して hour1weather を取得するユニバーサル メソッドを作成する方法はありますか?

4

2 に答える 2

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;
}
于 2012-10-29T17:54:58.640 に答える
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];
于 2012-10-29T17:53:51.027 に答える