Johannes Knust
Johannes Knust

Reputation: 1021

How to reduce the nesting of these if-conditionals?

i have a little problem :D i can't find the right words for searching so i wrote this question. how i get this shorter? I know with this logic || but how i could add more than 1 in one line? Thanks for time Best regards John

    bool b = [self NSStringContains:convert contains:@"Input"];
    if (b ==true)
    {
           bool b = [self NSStringContains:convert contains:@"Output"]; 
           if (b ==true)
           {
                     bool b = [self NSStringContains:convert contains:@"statecheck"]; 
                     if (b ==true)
                     {
                     ....
                     }
           }
     }

Upvotes: 2

Views: 129

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490488

In this case, you seem to need &&:

if ([self NSStringContains:convert contains:@"Input"] &&
    [self NSStringContains:convert contains:@"Output"] &&
    [self NSStringContains:convert contains:@"statecheck"])
{
   ...
}

For what it's worth, given bool b;, if (b==true) is always redundant -- just use if (b).

Upvotes: 6

vcsjones
vcsjones

Reputation: 141678

Probably something like this:

bool hasInput = [self NSStringContains:convert contains:@"Input"];
bool hasOutput = [self NSStringContains:convert contains:@"Output"];
bool hasStatecheck = [self NSStringContains:convert contains:@"statecheck"];
if (hasInput && hasOutput && hasStatecheck)
{
}

What you are using is, "if this condition, then check this condition, and this condition", etc. You can put these together with a logical AND, denoted by the &&.

Upvotes: 2

Related Questions