Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Functions and Optionals Functions Function Return Types

Michael Benson
Michael Benson
674 Points

Confused in returns.swift challenge (Swift Functions and Optionals) over code working in challenge but not in Xcode

//This is the answer to the challenge that worked.

func greeting(person: String) -> String{
    println ("Hello \(person)") // Interpolation is the \(person) part
}
greeting("Tom")


//This is the only way that I can get this code to work in Swift 2 - Version 7.0.1 (7A1001)
//The print vs println is obvious but the -> String is not
//I get a Invalid redeclaration of 'greeting' in xcode.
//The code below works.

func greeting(person: String) {
    print("Hello \(person)")
}
greeting("Tom")

1 Answer

Kristian Egebæk-Carlsen
Kristian Egebæk-Carlsen
8,902 Points

The code should not work since you assign a return type to the function with the statement '-> String. This tells the compiler that a return statement will be a part of the function. In your function there is no return statement, therefore the code is wrong. If you want code that can pass the challenge and work in Xcode it should look like this:

func greeting(person: String) -> String{
    return "Hello \(person)"
}
greeting("Tom")