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

Alan Grey
Alan Grey
1,856 Points

FizzBuzz generator: my answer differs from Amit's, but is it a correct answer?

My code differs from Amit's, is it still correct? The main difference is that mine requires a user input, and then returns FizzBuzz/Fizz/Buzz:

var input = 330

var dividedByThree = (input % 3) var dividedByFive = (input % 5)

if dividedByFive == 0 && dividedByThree == 0 { println ("FizzBuzz!") } else if dividedByFive == 0 { println ("Buzz") } else if dividedByThree == 0 { println ("Fizz") } else { println ("(input)") }

Thanks in advance for any replies!

3 Answers

Sean Lee
Sean Lee
5,196 Points

mine was very different as well. I used an index, array and while loop:

var index = 0
let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 60, 300]

while index < numbers.count {
    if numbers[index]%3==0 && numbers[index]%5==0 
         println("FizzBuzz")
    }
    else if numbers[index]%3==0 {
        println("Fizz")
   }
    else if numbers[index]%5==0 {
        println("Buzz")
    }
    else {
        println(numbers[index])
    }
    index++
}
Felix Salazar
Felix Salazar
3,879 Points

Yes, it should work; only detail: the var declarations should be in separated lines. Have you tested it in your playground?

var input = 330

var dividedByThree = (input % 3)
var dividedByFive = (input % 5)

if dividedByFive == 0 && dividedByThree == 0 { 
println ("FizzBuzz!") } 
else if dividedByFive == 0 { 
println ("Buzz") } 
else if dividedByThree == 0 {
 println ("Fizz") } 
else { println ("(input)") }
Frances Angulo
Frances Angulo
5,311 Points

I did this without defining the dividends - I realize that I didn't use switch statement, so the else may be unnecessary?

var number = 25

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("else")
}