Working through the control flow section on Treehouse the next topic is switch statements. It’s basically a more neat version of writing if else and else if statements. It’s also nicer than writing out logical operators at times because its more clear what the code is doing.

The examples given were based on an array of strings that we had. Abbreviating airport codes into strings was the values in the array.

let airportCodes = [“LGA”, “LHR”, “CDG”, “HKG”, “DXB”, “LGW”, “JFK”,“ORY”]

With our switch statements we are replacing these strings with the city the airport code  is from. The most visible way to see how a switch statement works is if we made a for in loop named airportCode.  So we can see how each line of code is being used. A var for airport code is being created with the first string in the array. Since the index value 0 matches up in this first case “LGA” the console will print “New York”. When the for loop creates a var with the string “DXB” since no case matches the default case is executed and nothing crashes. The console prints “Don’t know what city that is in”.

for airportCode in airportCodes {
switch airportCode {
     case “LGA”: print(“New York”)
     default: print(“Don’t know what city that is in”)
// what the for in loop writes every time
// var airportCode = “LGA”
// var airportCode = “LHR”…
//since this matches case “LGA” print(“NewYork”) is executed
         }
}

This would just be the first case of the switch statement, but switch statements like a dictionary have a default case. This is like and else statement where it will get executed if none of the above cases match and prevent the code from not compiling cause you always have at least once case that works.  Writing out the full example.

for airportCode in airportCodes {
    switch airportCode {
    case “LGA”, “JFK”: print(“New York”)
    case “LHR”, “LGW”: print(“London”)
    case “CDG”, “ORY”: print(“Paris”)
    case “HKG”: print(“Hong Kong”)
    default: print(“I don’t know which city that airport is in”)
          }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s