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 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
9,189 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")