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
Jason Larkin
13,970 PointsSWIFT for/if statement not working
This looks like it SHOULD work, but doesn't. Can anyone shed some light on why this isn't passing please? Thank you.
let months = [1, 2, 3]
for month in months {
if months == 1 {
println("January")
} else if months == 2 {
println("February")
} else if months == 3 {
println("March")
}
}
2 Answers
Flor Antara
12,372 PointsYou should use month variable instead of months for the if else statement. Because months is your array and month is the value of each element of your array in a particular iteration.
I also highly recommend you to use a switch statement instead of if-else, this will produce a more readable code.
switch month {
case 1:
println("January")
case 2:
println("February")
case 3:
println("March")
// add the other cases
}
Hope this help.
Christian McMullin
13,086 Pointsyou are recalling items out of your array months so in order to do that you must call the name of the array with the index number like below.
remember when calling items from an array the first item is 0 and the second item is 1.
let months = [1, 2, 3]
for month in months {
if month == months[0] {
println("January")
} else if month == months[1] {
println("February")
} else if month == months[2] {
println("March")
}
}
Holt Hunter
4,629 PointsHolt Hunter
4,629 PointsWhat kind of error does the console show?