Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Can we use a Switch instead of a if else? And if yes, how do we do it?

This question is regarding the Fizzbuzz challenge. Can we use a Switch instead of a if else? And if yes, how do we do it?

1 Answer

Hi Azizi Khalid ,

Yes we can.

Sometimes is better to use switch statement and sometimes its better to use if , else.

Heres how we would use switch statements

Switch statements run over and over and search of the name or whatever its there . So e.g. if you tell Whats your name , and the user input is Annie , and you got Annie in switch statement , it will go and look for it and you can output message you want .

If your working with names you pass the name to the switch (value) so it knows that you want to look for that.

switch(value) {
    case condition1:
        // conditional code
        break;

    case condition2:
        // conditional code
        break;

    ...
    ...
    ...

    default:
        // default condition code (if any)
        break;
}

And heres if else :

In if else , you mostly use it like if you have a button , and you want an image to appear or disappear when its turned on or off, you then make its like if the button is on , make the image appear else make it disappear .

 if (<#condition#>) {
        <#statements#>
    } else {
        <#statements#>
    }

I hope this helped .