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 Syntax and Parameters

Troy Erby
Troy Erby
6,332 Points

Trouble calling Strings from functions

I'm getting an error message when I try to call a function where the variable is a string. It seems to work fine when the variable is an Int

func works (number:Int) {
    println("This works with \(number)")
}

works(8)  // so when I call the function in this statement everything goes smoothly




func fail (word:String) {
    println("This doesn't work with \(word)")
}

fail(Tom)   // I don't get an error until I try to call the func, at which time I get an error message which says, "Use of unresolved identifier 'Tom'

can someone help me understand what I'm missing. Thanks in advance.

3 Answers

Damien Watson
Damien Watson
27,419 Points

Hey Troy,

Your function 'fail' is looking for a string. You define a string by surrounded in quotes. Otherwise it will take 'Tom' to be a variable and try to resolve it. Try instead:

fail("Tom")
Michael Hulet
Michael Hulet
47,913 Points

When you're calling it, you're not passing in a String properly. Strings go in double quotes. Instead, the compiler thinks you're trying to reference a variable named Tom. Try calling it like this:

//Despite the function name, this will work
fail("Tom")
Damien Watson
Damien Watson
27,419 Points

Haha, good point Michael. Does that mean it is currently working as expected?

Michael Hulet
Michael Hulet
47,913 Points

I haven't tested it in a playground, but everything else looks good to me. I'd bet my hat that it works

Troy Erby
Troy Erby
6,332 Points

Bingo, that did the trick. Thanks for the help.