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 Collections and Control Flow Control Flow With Conditional Statements Working With Switch Statements

Gilang Ilhami
Gilang Ilhami
12,045 Points

Working with statements in Swift, not appending

I already set in the values in the append, but i don't know why it'a not working

operators.swift
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 countyCode {
      case "BEL", "LIE", "BGR": europeanCapitals.append("Brussels", "Vaduz", "Sofia")
      case "IND", "VNM": asianCapitals.append("New Delhi", "Hanoi")
      default: otherCapitals.append("Wahington D.C.", "Mexico City", "Brasilia")
      }
    // End code
}

I think .append() only works for adding a single element (string). Your sample works for me when I use this instead:

case "BEL", "LIE", "BGR": europeanCapitals += ["Brussels", "Vaduz", "Sofia"]

(see http://stackoverflow.com/questions/24002733/add-an-element-to-an-array-in-swift)

Here you should append whatever you want in a for loop. You can only append one element.

1 Answer

Abdulwahab Alansari
Abdulwahab Alansari
15,151 Points

First of all, you are using switch on countyCode, which does not exist in your code, I believe you meant to use "key". Second, you can only use one element in append() function. What's more, instead of listing all capitals in each append() function, just use "value".

You code should look like this:

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 "BEL", "LIE", "BGR": europeanCapitals.append(value)
    case "IND", "VNM": asianCapitals.append(value)
    default: otherCapitals.append(value)
    }
    // End code
}

Yeah that is correct. Nice explanation Abdulwahab Alansari!!