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 trialMichael McChesney
939 PointsSwitch Conditional: Can the case value be a variable or does it have to be a string? Ex. variable a versus 'a'?
Can the case value be a variable or does it have to be a string? Ex. variable a versus 'a'?
1 Answer
Robert Bojor
Courses Plus Student 29,439 PointsHi Max,
The variable goes always as the switch parameter and the case values are always constants. However, you can declare a constant and use that one in the case statement, like in the code below. It is an elegant solution since you can use an enum or constants declared in a header file for better control over the entire app...
int testVar = 1;
static int const secondVar = 2;
switch (testVar) {
case secondVar:
NSLog(@"Not equal");
break;
}
Using variables on both sides of the equation kind of defeats the purpose of the switch statement, use if-else if both sides are variable.