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 Collections and Control Flow Control Flow With Conditional Statements FizzBuzz Challenge

Taylor Thurston
Taylor Thurston
2,909 Points

I have exactly what's written in the video (except I have tried it using both i and n. It tells me my logic is wrong.wtf

for i in 1...100 { if (i % 3 == 0) && (i % 5 == 0) { print("FizzBuzz") } else if (i % 3 == 0) { print("Fizz") } else if (i % 5 == 0) { print ("Buzz") } else { print(i) } }

That's my function. Runs in xcode just fine...

fizzBuzz.swift
func fizzBuzz(n: Int) -> String {
  // Enter your code between the two comment markers
  for n in 1...100 {
    if (n % 3 == 0) && (n % 5 == 0) {
        print("FizzBuzz")
    } else if (n % 3 == 0) {
        print("Fizz")
    } else if (n % 5 == 0) {
        print ("Buzz")
    } else {
        print(n)
    }
}
  // End code
  return "\(n)"
}

1 Answer

You have 3 issues with your code.

  1. You are checking the Int 'n' and not a range of 1-100. Remember 'n' is a undetermined Int which will be passed in when the function is called. If you were running through a range of numbers every time when the function is called there would be no point to having the n parameter.
  2. You must return and not print
  3. The default is already taken care of for you so you can delete your last 'else'.

In cases like this especially when you start working on your own projects the best thing to do is go back slowly over what you are trying to do and check each detail. I find that actually talking through what you're doing out loud can also help, basically just explain what you are doing and why.

func fizzBuzz(n: Int) -> String {
  // Enter your code between the two comment markers
     if (n % 3 == 0) && (n % 5 == 0) {
        return("FizzBuzz")
    } else if (n % 3 == 0) {
        return("Fizz")
    } else if (n % 5 == 0) {
        return ("Buzz")
    }
  // End code
  return "\(n)"
}