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

thomas howard
thomas howard
17,572 Points

I can't figure out how to return the tuple elements. I don't think it was covered in the video before this question.

I tried putting the elements in () and had them separated by a colon. Not sure how to get it to return.

tuples.swift
func greeting(person: String) -> String {
    let language = "English"
    let greeting = "Hello \(person)"

    return (greeting: String, language: String)
}

2 Answers

Stone Preston
Stone Preston
42,016 Points

Task 1 states: Currently our greeting function only returns a single value. Modify it to return both the greeting and the language as a tuple. Make sure to name each item in the tuple: greeting and language. We will print them out in the next task.

so instead of returning a string, we need to return a tuple with 2 members inside it. they both need to be Strings and they need to be named greeting and language, in that order.

we can add the return type of tuple by placing (greeting: String, language: String) after the ->

func greeting(person: String) -> (greeting: String, language: String) {
    let language = "English"
    let greeting = "Hello \(person)"

    return greeting
}

however, we still need to change the return value at the end of the function to actually return this tuple. We can do this by placing (greeting, language) after the return keyword. this will return the language string and greeting string constants that get set inside the function as a tuple

func greeting(person: String) -> (greeting: String, language: String) {
    let language = "English"
    let greeting = "Hello \(person)"

    return (greeting, language)
}

note that you do not include the type of the members in the return statement, just the return value in the function header

see the Swift eBook for more information on tuples

thomas howard
thomas howard
17,572 Points

I see, place the value to be returned in the header of the function before putting it in the return.

Thanks, it worked!