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 Exercise: FizzBuzz Generator

Jannik Spiessens
Jannik Spiessens
13,229 Points

is this a better or worse way to make the FizzBuzz generator?

for i in 1...20 {
    if i % 3 == 0 {
        print("Fizz")
    }
    if i % 5 == 0 {
        print("Buzz")
    }
    if i % 5 != 0 && i % 3 != 0 {
        print(i)
    }
    println()
}

I am using the print() function in stead of the println() function to make the "Buzz" stand behind the "Fizz".

2 Answers

My code looks like:

func fizzbuzz(#number: Int){
if number % 3 == 0 && number % 5 == 0 {
    println("FizzBuzz")
} else if number % 5 == 0 {
    println("Buzz")
} else if number % 3 == 0 {
    println("Fizz")
} else {
    println("No fizzing, buzzing, or fizzbuzzing for you!")
}
}

I then tested it with a loop:

for var i = 0; i < 50; i++ {
    fizzbuzz(number: i)
}

I hope that helps.

Steve.

May I also add the one addition:

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

This lets you see each number for a bit more clarity.