Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

What are the differences between if and switch operator?

What are the differences between if and switch operator? What are the advantages and disadvantages?

1 Answer

Brenden Konnagan
Brenden Konnagan
16,858 Points

They are both control flow statements.

Perhaps this will help:

let testValue = true

You will notice that testValue is a Bool assigned to true.

But what if you want to build logic on that? Traditional if / else statements might look like this:

if testValue {
    // Do something for testValue is true
} else {
    // Do something for testValue is false
}

Where a switch statement can be written like so:

switch testValue {
    case true:
        // Do something
    case false:
        // Do something
}

Really it is a matter of style, and logic. If you are testing for one condition, then a simple if / else statement might work. Otherwise, switch statements give you power to concisely and clearly express your intentions for a number of scenarios. This becomes very evident in a long if / else statement like:

if someValue {
    // Do something
} else if someOtherCondition {
    // Do something
} else {
   // Do another thing
}

There are of course more advanced things you can do with switch statements as well, and coupled with Enums are quite powerful. I would recommend checking out the Apple Swift E-Book under the chapter on control statements for a further look at the switch statement.

Hope this helps!

Cheers!

I didn't notice your answer until now. Thank you so much this was very helpful. it's confusing sometimes because there are so many similarities.