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 Basics (retired) Control Flow If Statement

Sammy Lammy
Sammy Lammy
2,011 Points

if statement

You are provided with a constant array named months that contains 3 consecutive numbers starting at 1. Using a for-in loop and an if statement, print out "January" when you encounter a 1, "February" when you encounter a 2, and finally "March" when you encounter a 3.

i can't figure this challenge out :(

months.swift
let months = [1, 2, 3]

for month in months{
  println(month)
}

for month in months{
  if month == 1 {
  println("January")
} else if month == 2 {
  println("February")
} else month == 3 {
  println("March")
}

2 Answers

Emil Rais
Emil Rais
26,873 Points

The last case of your if is invalid. If you want to add another condition you should use "else if" followed by the condition. If you want to add a "catch all remaining cases" you should use "else". You cannot use "else" with a condition.

Try this:

let months = [1, 2, 3]
for month in months {
    if month == 1 {
    println("January")
    } else if month == 2 {
        println("February")
    } else {
        println("March")
    }
}

Hope this helps

Paul Brazell
Paul Brazell
14,371 Points

While this will resolve the issue, this is also giving the impression that any month other than month 1 and 2 will equal march. Best to do the else if in this case.