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 trial

iOS Swift 2.0 Collections and Control Flow Control Flow With Conditional Statements The Power of Switching

Mert Kahraman
Mert Kahraman
12,118 Points

Confused about logical operations about the multiple values on case statements

I'm unsure switch statement cases use an AND or an OR operator while inputting multiple values and seperating them with commas.

In the video, we were shown that we can write more than one item on each case statement, to be checked/compared with the main variable/constant on our switch statement. For example: switch airportCode { case "LGA", "JFK": print("abc") .... }

In here we input two strings on a single case to be compared with airportCode. Are these compared using an AND or an OR statement? In other words, does this actually mean --> if ( "LGA" && "JFK" ) is TRUE, then print..
or does this mean --> if ( "LGA" || "JFK" ) is TRUE, then print..

If it's actually an OR statement, how do we indicate an AND statement on these cases in switch statements? Can we write the following:

switch airportCode { case "LGA" && "JFK": print("abc") .... }

I will appreciate your help, thanks!

1 Answer

Rodrigo Chousal
Rodrigo Chousal
16,009 Points

Hey Mert,

On the AND vs. OR question, definitely OR. What the switch statement does is compare the airportCode to the cases given. So, if airportCode matches any of the cases you gave, it will execute print("abc"). You could just as easily write the switch statement as:

 switch airportCode {
        case "LGA": print("abc")
        case "JFK": print("abc")
}

// Instead of

switch airportCode {
        case "LGA", "JFK": print("abc")
}

and it would mean the same thing. That said, if the airportCode matches "LGA" OR "JFK", it will print "abc".

What you are trying to say wouldn't make sense to attempt in a switch statement. Switch statements are used for comparing a single value against another, so trying to match one airportCode, let's say "LGA" to both "LGA" AND "JFK" wouldn't make sense.

Hope this helps, Rodrigo