Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift 2.0 Collections and Control Flow Control Flow With Conditional Statements Switch Statements

David Alvarez
David Alvarez
2,689 Points

Why printing "default" in last example?


When each one of the items of array are printing, the switch statement also print the "default" case. But...

Why it is printing the "default" case?

All the cases above are true and all are from the array.

Micah DeLaurentis
Micah DeLaurentis
3,534 Points

because not all of the elements in the array are considered in switch cases.

2 Answers

Nikki Bearman
Nikki Bearman
3,389 Points

Hi David,

All of the cases that are listed within the switch statement are true, however the switch statement is actually searching and presenting results for every value shown in the array you've named, based on the cases you've listed. In this case the array is the let airportCodes = statement:

let airportCodes = ["LGA", "LHR", "CDG", "HKG", "DXB"]

The following is the switch statement which searches the above array:

for airportCode in airportCodes {
    switch airportCode {
    case "LGA": print("New York")
    case "LHR": print("London")
    case "CDG": print("Paris")
    case "HKG": print("Hong Kong")
    default: print("I do not know which city this airport is in!")

In the switch statement we have a case for "LGA", "LHR", "CDG" and "HKG", but not for "DXB". This means that when "DXB" is found in the airportCodes array it then defaults (eg. presents "I do not know which city this airport is in!"). If you include

case "DXB": print("Dubai")

after the HKG line then you will see that the default will no longer show up in your results and instead you will see "Dubai".

In summary, whenever a value from the named array is not found within the case list of the switch statement, it will fall to the default you've supplied. Hope that makes sense/helps.