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

Raphael Reiter
Raphael Reiter
6,820 Points

working with switch statements challenge

hey guys, im stuck. anyone has the answer to this challenge? cheers R

2 Answers

Matthew Young
Matthew Young
5,133 Points

I believe this is the correct answer:

The for statement is declaring the variables with the "world" dictionary as "key" for the Key and "value" as the Value associated with "key". The switch statement is then taking the current value for "key" and comparing it to the cases defined within the closure of the switch statement. If "key" matches any of the cases, then the respective code is executed.

For example, the first key that's used is "BEL". "BEL" matches the first case in the switch closure so the code "europeanCapitals.append(value)" is executed. The result of that code is the value of "value", which in this example is "Brussels", gets appended to the "europeanCapitals" array.

The default case in the switch statement is for anything that doesn't match up with the other specified cases (for example, "USA").

The for closure is then repeated for as many Keys as there are in the Dictionary (which is 8).

for (key,value) in world {
    switch key {
    case "BEL","LIE","BGR": europeanCapitals.append(value)
    case "VNM","IND": asianCapitals.append(value)
    default: otherCapitals.append(value)
    }
}

Put each key on seperate cases. Worked for me

var europeanCapitals: [String] = []
var asianCapitals: [String] = []
var otherCapitals: [String] = []

let world = [
  "BEL": "Brussels", 
  "LIE": "Vaduz", 
  "BGR": "Sofia", 
  "USA": "Washington D.C.", 
  "MEX": "Mexico City", 
  "BRA": "Brasilia", 
  "IND": "New Delhi", 
  "VNM": "Hanoi"]

for (key, value) in world {
    // Enter your code below
    switch key {
      case "LIE": europeanCapitals.append(value)
      case "BEL": europeanCapitals.append(value)
      case "BGR": europeanCapitals.append(value)
      case "VNM": asianCapitals.append(value)
      default: otherCapitals.append(value)
    }
    // End code
}