-2

I am trying to run this code but it's not working. I don't know how to return the input j as a string. This is the error /tmp/D2FFE31F-B533-48DF-AC15-F1EA8A029FCF.q0h9za/main.swift:15:1: error: missing return in a function expected to return 'String'

func FizzBuzz(j:Int) -> String {
if j % 5 == 0 && j % 3 == 0 {
    return "FizzBuzz"
}

else if j % 3 == 0 {
    return "Buzz"
}

else if j % 5 == 0 {
    return "Fizz"
}
}

for i in 0...100 {
print(FizzBuzz(j:i))
}
Cool coder
  • 13
  • 4
  • Didn't downvote, but you're missing a `)` at the end of `print(FizzBuzz(j:i)` – aheze Feb 02 '21 at 01:10
  • Sorry Aheze i did it in the IDE but I guess it didn't load. But if you want to know the error this is it. /tmp/D2FFE31F-B533-48DF-AC15-F1EA8A029FCF.q0h9za/main.swift:15:1: error: missing return in a function expected to return 'String' – Cool coder Feb 02 '21 at 01:11
  • 3
    I didn't downvote, but I do think your question could be improved. In particular, you should change the title to something more specific, like "convert Int to String". – rob mayoff Feb 02 '21 at 01:13

3 Answers3

1

Adding on to @rob mayoff's answer, the problem is also that you must return a string in that function, because you said so:

                        // must return a String
func FizzBuzz(j:Int) -> String { 

So look in your function. What if j is not divisible by 5, or 3? Your code will just fall through the if else, and none of the returns will be called.

To fix this, just do a return at the end of your function.

func FizzBuzz(j:Int) -> String {
    if j % 5 == 0 && j % 3 == 0 {
        return "FizzBuzz"
    } else if j % 3 == 0 {
        return "Buzz"
    } else if j % 5 == 0 {
        return "Fizz"
    }

    return "\(j)" /// return the number
}
aheze
  • 24,434
  • 8
  • 68
  • 125
0

Swift strings have a feature called “string interpolation”. When a string contains the characters \( followed by some expression followed by ), Swift evaluates (runs) the expression and converts the result to a string, and substitutes that result string into the enclosing string. For example:

"two plus three is \(2 + 3)"

Above, Swift computes 2 + 3, getting the Int 5, then converts the Int 5 into the string "5", then substitutes that into the enclosing string, getting "two plus three is 5".

So one way to return j as a string is to use string interpolation like this:

return "\(j)"
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
0

Short answer: “if” statements always need an “else” to return a result.

You have 3 if/else if statements, but no final “else” if those fail.

You need to add either

else {
   return “”
}

Or just a final

return “”
Dharman
  • 30,962
  • 25
  • 85
  • 135
Nicholas Rees
  • 723
  • 2
  • 9