+ 1

What is the point of a switch statement?

I am thoroughly confused about why one might use a switch statement over and if statement. I also don't get how to use it with the where function. I'm still unsure of why it is called switch, too, since it doesn't switch the value of a variable. Can someone help me?

22nd Nov 2016, 8:57 PM
Winnie
3 ответов
+ 2
The switch performs faster and is particularly used for the situation when you are comparing the same variable or expression to be equal to many possibilities. You can even group multiple cases together. Instead of saying if (x == 1) { .... } else if (x == 2 || x == 3) { ... } else etc.... you simply have one switch statement with cases switch (x) { case 1: ... break; case 2, 3: ... break; default: ... } the default statement and section are optional
23rd Nov 2016, 5:40 AM
David-Hesh Hochhauser
David-Hesh Hochhauser - avatar
+ 1
It's used sometimes over an if statement because it's easier. Whether it's faster or not, I'm not sure. Imagine typing if (x==5) {} (using C++ syntax, not sure about swift) a few times with different values to replace the 5. Now imagine just using switch. It's much simpler and easier to read. It's called switch (as far as I know) because if one case statement is false, it'll switch to the next one. Regarding the where function, I might be wrong because I haven't studied swift but it should just be something similar to this. switch (x) { case 2: cout << "x is 2!"; break; case 5: cout << "x is 5!"; break; default: cout << "x isn't 2 or 5!"; };
22nd Nov 2016, 9:05 PM
Ben
Ben - avatar
0
I think i get the where function now, but not sure why you would use switch
22nd Nov 2016, 9:00 PM
Winnie