Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Collections and Control Flow Control Flow With Conditional Statements FizzBuzz Challenge

Jericoe States
Jericoe States
3,262 Points

FizzBuzz

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) {

        print("Fizz")

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

        print("Buzz")

    } else {
}

return "\(n)"

}

}

// I don't know what I'm doing Wong? Can someone help?

fizzBuzz.swift
func fizzBuzz(n: Int) -> String {
    for n in 1...100 {
        if (n % 3 == 0) && (n % 5 == 0) {
            return("FizzBuzz")
        } else if (n % 3 == 0) {
            print("Fizz")
        } else if (n % 5 == 0) {
            print("Buzz")
        } else {
    }

    return "\(n)"
}

3 Answers

Ryan Sady
Ryan Sady
20,594 Points

You have a few different things going on here...

First of all, your function should return an Int, not a String. Next, you want to print("FizzBuzz"), not return it.
You're also missing a closing brace at the end, but that was because you had the return declaration in the wrong part. Here's the correct code...

func fizzBuzz(n: Int) -> Int {
    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)")
        }
    }

    return n
}

And to call the function:

fizzBuzz(n: 100)
Jericoe States
Jericoe States
3,262 Points

func fizzBuzz(n: 100) -> Int {

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)")

    }

}

return n

}

// something like that ?

Ryan Sady
Ryan Sady
20,594 Points

You don't want to return the "Fizz" and "Buzz". You need to return n to the main function for the input variable. You need to print "Fizz" and "Buzz". Also when declaring a function, you don't put in your variables value. When declaring the function, it should read n: Int.

Your code should look exactly like the code I provided.