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

This code is correct right?

Hey guys, I'm doing the FizzBuzz challenge and I really don't want to look to the solutation, so I hope one of you guys can explain me what I'm doing wrong, the bummers says: Double check your logic for FizzBuzz values and make sure you're returning the correct string! Thanks.

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

    }
    if (n % 3 == 0) && (n % 5 == 0) {
        return "FizzBuzz"
    }

    // End code
    return "\(n)"
}

2 Answers

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hey Justus,

You've got the syntax right, it's just the order that the conditionals are checking the logic. Remember, that once a condition returns true, the compiler stops checking.

With that in mind, if a number is divisible by 3 (as your first condition is checking for), the compiler stops and will not check to see if it is also divisible by 5. So, you just need a little bit of a reorder of the conditionals to make sure the number can be checked for both 3 and 5.

Hope that helps to explain it for you. :)

Keep Coding! :dizzy:

Julien riera
Julien riera
14,665 Points

Hello,

You're almost there!

You miss the order the code checks your conditions. Try this conditional instead:

if n % 3 == 0 && n % 5 == 0 {
    print("FizzBuzz")
} else if n % 3 == 0 {
    print("Fizz")
} else if n % 5 == 0 {
    print("Buzz")
}

If you need more explanation, feel free to ask about it.

Otherwise, just let us know if that solves the issue you're having.

Cheers,

Julien