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 trialJonathan Lee
1,565 PointsFizzBuzz
Works in the playground perfectly.
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) { //Have to put FizzBuzz first
return("FizzBuzz")
} else if (n%5 == 0){
return("Buzz")
} else if (n%3 == 0){
return("Fizz")
} else {
return(n)
}
}
// End code
return "\(n)"
}
Kehinde Fatoki
822 Pointsi used the same code and could not find what was wrong with it so here is a new one
var s: String = " "
if( n % 3 == 0) && (n % 5 == 0) {
s = "FizzBuzz"
} else if ( n % 3 == 0) {
s = "Fizz"
} else if (n % 5 == 0) {
s = ("Buzz")
}
//change the return "(n)" to return "(s)
3 Answers
Schaffer Robichaux
21,729 Pointsif n % 3 == 0 && n % 5 == 0 { return ("FizzBuzz") } else if n % 3 == 0 { return ("Fizz") } else if n % 5 == 0 { return ("Buzz") }
Jonathan, you are 100% correct- you're code compiles perfectly; however, you are receiving an error due to the specificity of the instructions- removing your last else statement should satisfy the challenge. I feel your pain- I wrestled with the same challenge for well over an hour. Cheers
Jonathan Lee
1,565 PointsThank you both!
harryg2
5,792 PointsThe compiler is saying that it cannot return the constant n
as type Int
, because you have told your function you will be returning a String
value. The best way to solve this problem is to take your line return(n)
and use string interpolation to convert it from an Int
to type String
(ie. return("\(n)")
).
In the end, you may have something similar to this...
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")
} else {
return("\(n)")
}
}
Jonathan Lee
1,565 PointsJonathan Lee
1,565 Pointsswift_lint.swift:13:16: error: cannot convert return expression of type 'Int' to return type 'String' return(n) ~^~
This is the error that shows up in the code challenge preview.