Evgeniy Kleban Evgeniy Kleban - 3 months ago 18
Objective-C Question

Control reach end of non-void function

Please consider following code:

-(NSString*)getNextOvulationString{

if (self.daysToNextOvulation < 0){
return [NSString stringWithFormat:@"Овуляция была %li дней назад", labs(self.daysToNextOvulation)];
} else if (self.daysToNextOvulation == 0){
return [NSString stringWithFormat:@"Овуляция началась"];
} else if (self.daysToNextOvulation > 0){
return [NSString stringWithFormat:@"Овуляция началась"];
}
}


There is 3 cases, and obvious, we will get one guaranteed.

Still, compiler not allow me to build, because of error:


Control reach end of non-void function


How to fix that?

Answer

Since the final condition is the exhaustive case, change the final else if to an else and call it a day. If you want, add your condition as a same-line comment to keep it clear.

The end result would be something like this:

- (NSString *)getNextOvulationString
{
    if (self.daysToNextOvulation < 0)
    {
        return [NSString stringWithFormat:@"Овуляция была %li дней назад", labs(self.daysToNextOvulation)];
    }   
    else if (self.daysToNextOvulation == 0)
    {
        return [NSString stringWithFormat:@"Овуляция началась"];
    }   
    else // self.daysToNextOvulation > 0
    {
        return [NSString stringWithFormat:@"Овуляция началась"];
    }
 }

You could also drop the final else altogether like this:

- (NSString *)getNextOvulationString
{
    if (self.daysToNextOvulation < 0)
    {
        return [NSString stringWithFormat:@"Овуляция была %li дней назад", labs(self.daysToNextOvulation)];
    }   
    else if (self.daysToNextOvulation == 0)
    {
        return [NSString stringWithFormat:@"Овуляция началась"];
    }   

    // self.daysToNextOvulation > 0
    return [NSString stringWithFormat:@"Овуляция началась"];
 }

And since the last two conditions both return the same thing you could even write it this way:

- (NSString *)getNextOvulationString
{
    if (self.daysToNextOvulation < 0)
    {
        return [NSString stringWithFormat:@"Овуляция была %li дней назад", labs(self.daysToNextOvulation)];
    }
    else // self.daysToNextOvulation >= 0
    {
        return [NSString stringWithFormat:@"Овуляция началась"];
    }
 }

Or this way, again dropping the else entirely:

- (NSString *)getNextOvulationString
{
    if (self.daysToNextOvulation < 0)
    {
        return [NSString stringWithFormat:@"Овуляция была %li дней назад", labs(self.daysToNextOvulation)];
    }

    // self.daysToNextOvulation >= 0
    return [NSString stringWithFormat:@"Овуляция началась"];
 }

Note: All of the above pieces of code are functionally equivalent given the current conditions and return values.

Comments