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 Swift Enums and Structs Enums Associated Values

Frances Angulo
Frances Angulo
5,311 Points

case/switch vs. if statements for enum cases

Why did we use this code:

switch downloadStatus {
case .Success(let success):
case .Failure(let failure):

instead of an if statement with cases/else/returns?

3 Answers

i think switch reduces amount of code

Brandon Meyer
Brandon Meyer
2,793 Points

I'm fairly new and ignorant to programming concepts but would it be that Switch is the new if\else statement? Since with Switch we can do if/if-else/else without having to change our code if a new option comes up in the if statement.

As I said I may be way off but it seems the Switch is more dynamic in what you can do.

Ilari Niitamo
Ilari Niitamo
6,458 Points

Switches exist alongside if-else statements. How you use them is your own convenience. In some cases switches may reduce the amount of code and make it more readable, in other cases it may look cumbersome and weird. There are minute differences, but I would say they only matter to a bit more advanced stuff, and by convenience even then.

I've always preferred if-else to switch. Switch is kinda like the foreign cousin of if-else, for and while, since it looks so different. Also, I vehemently hate the way you usually have to add a break-line for each case. Apparently in Swift breaking is no longer necessary, so I'm gonna have to reassess my prejudices :).