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

Better Help?

I need some help.

  1. I don't understand what return is needed for. I understand how to make functions I just don't understand why we need returns and how to make them could someone help me. Also, I am wondering what might be wrong with my code. Thanks, Josh
returns.swift
func greeting(person: String,hello: String )-> string {
    return hello, person
}

greeting(Tom,Hello)
chunchang pan
chunchang pan
4,319 Points

You can rewrite your code like below. I think this is what you want. func greeting(person: String,hello: String )-> String { return "(hello), (person)" }

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,703 Points

Not all functions return something. Sometimes they just perform an action inside the function, which is the case with the function they gave you to start with that had "println("Hello (person))".

There are a few things wrong with your code:

1) It should take only one argument: (person: String). That's the part that is going to change depending on the name of the person you pass in. The word "hello" is always going to be the same.

2) The "string" that you specify as the return value needs to be capitalized: " -> String "

3) when you return the string inside the function, it needs to be in quotes, and you need to use string interpolation for the "person" variable - like this

 return "Hello \(person)"

Also, the word "Hello" needs to be capitalized. The swift language doesn't care, but this code challenge does. They also want the phrase without a comma.

The whole thing should look like this:

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

The advantage of having a function return something is that you can you that returned value and put it into a variable, or you can pass it into another function. That way your function could be part of a chain of events.

So you could do something like this later:

var greetingOutput = greeting("Dave") // This takes "Hello, Dave" and puts it inside the variable 'greetingOutput'

println(greetingOutput) // this takes that string you made and passes it into the println function