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 trialjames white
78,399 PointsFizzBuzz casting
I tried this code:
for n in 1...100 {
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
}
}
..and it gave me this error:
swift_lint.swift:13:16: error: cannot convert return expression of type 'Int' to return type 'String'
return n
^
So I figured that meant I had to do some type casting.
This StackOverFlow thread was helpful in figuring out how to do the string conversion:
http://stackoverflow.com/questions/24161336/convert-int-to-string-in-swift
So based on the above StackOverFlow thread where it had this line:
var myString = String(x)
I then decided to try this code:
for n in 1...100 {
if (n % 3 == 0) && (n % 5 == 0) {
return "FizzBuzz"
} else if (n % 3 == 0) {
return "Fizz"
} else if (n % 5 == 0) {
return "Buzz"
} else {
var myString = String(x)
return myString
}
}
..which gave me this Bummer:
Bummer! Double check your logic for Fizz values and make sure you're printing the correct string!
So it wants printing? Huh?!
I thought Step 3 said:
Step 3: Change all your print statements to return statements.
But if it wants print statements then I'll add back the print statements:
for i in 1...100 {
if (n % 3 == 0) && (n % 5 == 0) {
print("FizzBuzz")
return "FizzBuzz"
} else if (n % 3 == 0) {
print("Fizz")
return "Fizz"
} else if (n % 5 == 0) {
print("Buzz")
return "Buzz"
} else {
print(i)
var myString = String(i)
return myString
}
}
Note: I also figured (re-reading the challenge instructions very carefully),
I would change back some of the 'n' occurrences back to 'i'
and I somehow got it to pass (don't really know why though? --but whatever.. )
1 Answer
Pasan Premaratne
Treehouse TeacherThis course simply builds on top of everything taught so far and since we haven't covered casting the challenge doesn't specifically look for that.
The starter code for the challenge already returns the else case as a string which is why you're running into the error.
return "\(n)"
It uses simple string interpolation instead of casting.