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 Switch Statements

David Alvarez
David Alvarez
2,689 Points

Why printing "default" in last example?

Hello:

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.

Nikki