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 trialCory Waldroup
3,609 PointsAppending results to the appropriate array
I am getting an error stating that I am not appending the results of each case to the correct array, but in Playgrounds this code produces the correct results.
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 {
switch key {
case "BEL", "LIE", "BGR": europeanCapitals += [value]
case "IND", "VNM": asianCapitals += [value]
default: otherCapitals += [value]
}
}
2 Answers
AJ Salmon
5,675 PointsHey Cory! You're using the string concatenation operand (+), but the variables europeanCapitals
, asianCapitals
, and otherCapitals
are not strings; they're arrays that contain strings. You can tell this because after the variables are declared, the type is explicitly defined. Because it says [String]
, in square brackets, it has to be an array. SO, instead of using + to try and concatenate non-existent strings, use the .append()
method to add the value to the array. Hope this helps!
AJ
Cory Waldroup
3,609 PointsThanks, AJ. I suppose I thought that by placing value in square brackets I was making it a single entry array of type String and then adding it to the europeanCapitals array of type String. I am very surprised that it worked in a Playground. I will use the method you suggested and appease the challenge, but I still thought it could be used either through calling the function append or by concatenation of two arrays of type String.
AJ Salmon
5,675 PointsHuh! I just tried your version out in a playground, and it does seem to work! I'm not super knowledgeable when it comes to swift types, but it appears that it's getting the exact same result, and that's definitely a smart way to do it. Sometimes, code challenges can tell whether specific keywords are used, like append
, for instance. That would be my guess as to why your code didn't pass the challenge; it wanted you to use the append method specifically. Another reason could be that the concatenation method unnecessarily creates a new array with a single element, whereas the .append()
adds it to the array directly. Regardless, glad I could help :)