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

Miguel Correia
Miguel Correia
1,216 Points

FizzBuzz question bug

In my FizzBuzz question I already tried to submit many answers but none of them seam to be right on treehouse exercise but in my xcode it is right, can some one help me with this one so I can proceed

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) {
        return "FizzBuzz"
    } else if (n % 3 == 0) {
        return "Fizz"
    } else if (n % 5 == 0) {
        return "Buzz"
    } else {
        return "\(n)"}
    }
}
 } else if (n % 3 == 0) {

        return "Fizz"

    } else if (n % 5 == 0) {

        return "Buzz"

I have a comment on this code, what you did there was the following If 15 (Our random number in this case) is divided by 3 is 0 then return Fizz

But 15/3 = 5

And 15/5 = 3

So i recommend using the remainder operation. This documentation by apple can help you a lot! (https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html)

Miguel Correia
Miguel Correia
1,216 Points

Sorry but I don't understand what you are trying to say

I just wanted to make clear that n % 3 will never be 0

nether does n % 5

You have to take the remainder of the division to decide whether or not it is divisible by 3 or 5.

When the remainder operation returns with a 1 it is dividable if not, it isn't.

I hope this makes it clear.

Miguel Correia
Miguel Correia
1,216 Points

alright but this was the actually answer of the question the instructor said in the next video, so strange how it doesn't work btw I did take the remainder out and it gives me an error on xcode now.

Hmmm strange

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Miguel,

As per the challenge task, you don't need a for loop in your function as it will take care of that for you. Instead, you just need the if statements in your current code and that's it.

func fizzBuzz(n: Int) -> String {
  if (n % 3 == 0) && (n % 5 == 0) {
    return "FizzBuzz"
  } else if (n % 3 == 0) {
    return "Fizz"
  } else if (n % 5 == 0) {
    return "Buzz"
  }

  return "\(n)"
}

Happy coding!