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 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):
    println(success)
case .Failure(let failure):
    println(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 :).