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

For-in-Loop Challenge help!

Still having trouble with this Challenge. They were looking for [January, February, March] but instead, my print reads as [January 1, February 2, March]

where does the 1 & 2 in my print come from and how to resolve it?

I'm sorry for the re-post of this. just desperately need the help.

Thank you!

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

  else {
    println(month)
    }
    }

2 Answers

Hi Jesse,

It helps if you format your code with the normal indentation. I don't know if XCode Playgrounds have an autoformatter, but I did it manually for your code:

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

The extra numbers are coming from the final else clause. Remove that and you should be good to go.

The way I formatted it, it might be clearer that the else only applies to the last if condition, not the first two. If you wanted to chain together all of the if statements so that the final else did apply to them all, you'd need to use several else ifs:

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")
  } else {
    println(month)
  }
}

It's because your January and February if statements are separate from the March if statement so the else condition is true when month is 1 or 2.