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 trialCaleb Shook
2,357 Pointsfunc greeting(person: String) -> String { return println("Hello \(person)") } What is wrong with this?
i am supposed to be making the function return a string that is a greeting. If I set the parameters to Tom is should return Hello Tom. But it says the code could not be compiled and I do not know why.
func greeting(person: String) -> String {
return println("Hello \(person)")
}
3 Answers
Iulian Popescu
1,363 PointsYou return the result of println, which will be nothing and for sure is different than String. This is why your code is not compiling. To solve it just remove the println statement and it should work perfectly.
Caleb Shook
2,357 PointsThank you! That worked perfectly! Is there any resource you could provide me that explains that better as to why it doesn't work the way I did, or if you could go more in depth about it that would be extremely helpful!
Iulian Popescu
1,363 PointsFirst of all your returned value doesn't match with the signature of method. In any programming language, if a method says that will return a data type, then any other value return with a data type different than previous one will lead to a compile error. So, in particular for your problem, you have a method that returns a String and you are trying the value returned by println, which has no return value since it is a void method (Void comes from the ideea that a method without returning value is called a void function). With all the above we solve your compile error. Now, let's suppose that the println method will return a String after printing something (this is not happening), then your method will work fine without compile error.But now, let's think a little, if println returns some String on success then how can I be sure that I will return the value I want and not some weird value. Here was your second logical problem. Anyway if you still want in your method to be printed that String just insert before return a println with that value and it should work fine. And, as an advice never ever do not return the value of a other method without checking that the other particular method returns the data type you need. I hope that I was quite clear, but if I wasn't leave a message and I will respond asap. Good luck!