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!

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

Matt Brown
Matt Brown
7,782 Points

Function objective - what is wrong with my code?

I can't seem to figure out the logic for function inputs.

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

println("Hello \(greeting(Tom))")

1 Answer

Hey Matt,

Ok let's walk through the logic of the code sample you have given. You are defining a function which 'accepts' a variable. This is a variable that you pass in.

For example, the line below is saying you are going to pass in a variable called 'person' which is a string. When you call the function and pass in your variable, the variable you pass in takes the place of the variable 'Person'

func greeting(person: String)-> String

So for example, if the function adds a character to the string you passed in the function would look like this:

func greeting(person: String)-> String {
var randomString = person + " randomly added string"
return randomString

What this is doing, is getting the string you passed into the function and adding another string onto the string you passed in, we are then returning the result of this function which is the 'randomString' variable.

So for example, if your variable is:

var tom = "tom"

and you call the function like this

var finalString = greeting(tom) 

So what we are doing is passing in the string 'tom' this takes the place of the string we said we were going to pass into when we defined the function.

So this is what is logically happening:

func greeting(person: String)-> String {
//the variable we passed takes the place of 'person'
var randomString = tom + " randomly added string"
return randomString

The return statement will set the variable to what you returned. Think of the returned as the 'result'

I hope I have at least helped you understand a bit better.

Thanks, Alex