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 2.0 Collections and Control Flow Control Flow With Conditional Statements FizzBuzz

Jonathan Lee
Jonathan Lee
1,565 Points

FizzBuzz

Works in the playground perfectly.

fizzBuzz.swift
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)"
}
Jonathan Lee
Jonathan Lee
1,565 Points

swift_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.

Kehinde Fatoki
Kehinde Fatoki
822 Points

i 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
Schaffer Robichaux
21,729 Points

if 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

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