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 Objective-C Basics (Retired) Functional Programming in C Conditionals - Switch

Humza Choudry
Humza Choudry
237 Points

ELSE/IF or Switch case

As shown in the video Doug shows two different ways of shows the values. Why use switch when you can use the else if statement that is much shorter? Whats the difference? How is one better over the other if it is?

3 Answers

Patrick Cooney
Patrick Cooney
12,216 Points

They're pretty similar. One advantage to using a switch is that if you accidentally forgot to include a possible outcome the switch statement will execute the code in the default. This will likely give you the wrong result but at least it won't crash your app. If you were to use else if statements and you missed a potential outcome the app would crash there.

well for two choices you can indeed use if/else but for lots more choices if/else will take up too many lines and switch will be a more elegant solution.

of course as far as I know you will have to use if/else if a choice is a more complicated comparison as switch cant handle that

Humza Choudry
Humza Choudry
237 Points

Thank you both for the informative answer. Every answer helps. :D