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 trialBryan Anderson
1,062 PointsDon't exactly understand Switch
What does the Switch statement actually do? What is it comparable?
3 Answers
Kirill Pahnev
2,617 PointsSwitch 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
}
Erik McClintock
45,783 PointsBryan,
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
4,867 Pointsmaybe 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.
Daniel Sattler
4,867 PointsDaniel Sattler
4,867 PointsHow do you guys display code that way?
Geoff Parsons
11,679 PointsGeoff Parsons
11,679 PointsDaniel Sattler check out this post for some tips for formatting code on the forums.
Kirill Pahnev
2,617 PointsKirill Pahnev
2,617 PointsAlso below the Answer textfield is a "Markdown Cheatsheet" link.