我要回收什么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 ;
}
答案 0 :(得分:0)
这个怎么样?
- (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;
}
答案 1 :(得分:0)
这不是我如何真实地做到这一点,但在练习的背景下,这将是了解变量范围的好时机。你应该做的是在条件之外声明一个NSString。这样,当您在条件中分配或更改它时,它会保留其值。然后在条件内分配短语。完成后,返回短语。
- (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;
}
答案 2 :(得分:0)
老实说,我没有意识到让整个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
更简单。
答案 3 :(得分:-2)
- (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;
}