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 trialRyan Petrill
1,188 PointsI can't Figure Out What is Wrong
What's Wrong?
let months = [1, 2, 3]
for month in months {
if months[month] == 1 {
println("January")
} else if months[month] == 2 {
println("February")
} else if months[month] == 3 {
println("March")
}
}
1 Answer
Giacomo La Scala
5,537 PointsThe problem with your code is that the variable "month" that you create inside the for loop by writing "for month in months" is not an incrementing count variable (meaning it starts at 0 and increases by one every loop) but is a variable that holds the value indexed inside the array every time the loop runs. This means that when the loop runs 1 time its value is 1, since the first value of the array is 1 (it would be 4, per say, if you would have written "let months = [4, 2, 3]", being 4 the first value), 2 when ran for the second time and 3 when ran for the third time. To solve this problem simply access the month variable every single time the loop is run and compare it to your chosen values instead of selecting the value inside the array. Try this code, it should do the job.
let months = [1, 2, 3]
for month in months {
if month == 1 {
println("January")
} else if month == 2 {
println("February")
} else if month == 3 {
println("March")
}
}
If this explanation was unclear or something is still wrong, feel free to ask me anything by responding and I will do my best to help you!