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

Don't exactly understand Switch

What does the Switch statement actually do? What is it comparable?

3 Answers

Kirill Pahnev
Kirill Pahnev
2,617 Points

Switch is just another way to go through some value(s) and perform something when value is met

var value = 2
 switch value {
case 1:
// value is 1 do something
case 2:
// value is 2 do something
default:
// value is something else, do something
}

Same thing with if statement would be

if (value == 1) {
// value is 1 do something
} else if (value == 2) {
// value is 2 do something
} else {
// value is something else, do something
}
Daniel Sattler
Daniel Sattler
4,867 Points

How do you guys display code that way?

Daniel Sattler check out this post for some tips for formatting code on the forums.

Kirill Pahnev
Kirill Pahnev
2,617 Points

Also below the Answer textfield is a "Markdown Cheatsheet" link.

Erik McClintock
Erik McClintock
45,783 Points

Bryan,

The "switch" statement is effectively an alternative method of writing an "if" statement. If you have a lot of possible outcomes for a particular situation, an "if/else if/else" style statement can get very long and verbose and out of control very quickly. The truncated syntax of the "switch" statement provides an easier-to-read (and manage) syntax for the same structure.

Erik

Daniel Sattler
Daniel Sattler
4,867 Points

maybe it´s easier to understand with an example:

switch card {
    case 1: do this
    case 2: do that
    case 3: do something else
   ....
    default: do something, if nothing of the above applies
    }

case can be anything... String, Int, ... if a case is true, so if 1 is the current state or case, then "do this", if case 2 is currently true, then "do that".... and so on...

you can define as many cases as you want, important is that you also define a default, in case nothing applies....

i hope this helps. I highly recommend having a look at the SWIFT basic Course -> Control Flow This will explain it a lot better and easier to understand.