if else 和 NSString 语句的解决方法

Solution for if else and NSString statement

我为 return 输入了什么 NSString? 我要找的答案是 1 奶酪或 2 奶酪

- (NSString *) numberOfCheesesStringWithCheeseCount:(NSUInteger)cheeseCount 
{
    if (cheeseCount == 1) {
        /* WORK HERE, ASSUMING THERE IS 1 CHEESE */
        NSString *phrase = [NSString stringWithFormat:@"%ld", (long)cheeseCount];
        NSLog(@"%@ cheese", phrase);
    } else {
        /* WORK HERE, ASSUMING THERE ARE 2+ CHEESES */
        NSString *phrase2 = [NSString stringWithFormat:@"%ld", (long)cheeseCount];
        NSLog(@"%@ cheeses", phrase2);
    }

    /*
     (You will learn more about if/else statements in the next checkpoint.)
     */

    return ;
}
- (NSString *)numberOfCheesesStringWithCheeseCount:(NSUInteger)cheeseCount
{
    NSString *phrase = [NSString stringWithFormat:@"%ld cheeses", (long)cheeseCount];
    if (cheeseCount == 1)
    {
        phrase = [NSString stringWithFormat:@"%ld cheese", (long)cheeseCount];          
    }

    NSLog(@"%@", phrase);
    return phrase;
}

这个怎么样?

- (NSString *) numberOfCheesesStringWithCheeseCount:(NSUInteger)cheeseCount 
{
    NSString *result;
    if (cheeseCount == 1)   
    {
        //No real point in building this string piecewise. It will always be
        //the same thing, "1 cheese".
        result = @"1 cheese";
    } 
    else 
    {
        /* WORK HERE, ASSUMING THERE ARE 2+ CHEESES */
        NSString *result = [NSString stringWithFormat:@"%ld cheeses", (long)cheeseCount];
    }
    NSLog(@"Result = %@", result);
    return result;
}

这不是我实际执行此操作的方式,但在您的练习上下文中,这将是了解变量范围的好时机。你应该做的是在条件之外声明一个 NSString。这样,当您在条件中分配或更改它时,它会保留其值。然后在条件句中分配短语。完成后,return 短语。

- (NSString *)numberOfCheesesStringWithCheeseCount:(NSUInteger)cheeseCount
{
    NSString *phrase = nil;
    if (cheeseCount == 1)
    {
        phrase = [NSString stringWithFormat:@"%ld cheese", (long)cheeseCount];
        NSLog(@"%@", phrase);

    }
    else
    {
        phrase = [NSString stringWithFormat:@"%ld cheeses", (long)cheeseCount];
        NSLog(@"%@", phrase);

    }
    return phrase;
}

老实说,我不明白拥有整个 if else statement 这可以缩短为 if statement 的意义。我建议改为:

- (NSString *)numberOfCheesesStringWithCheeseCount:(NSUInteger)cheeseCount
{
    // We setup our string (phrase) already with the value "1 Cheese"
    NSString *phrase = @"1 Cheese"; 

    if (cheeseCount > 1) {
        // If the value of cheeseCount is greater than 1 then we update our value.
        phrase = [NSString stringWithFormat:@"%ld cheeses", (long)cheeseCount];
    }

    // Return our value for phrase.
    return phrase;
}

这段代码比整个代码读起来简单多了if else statement