Learn
Functions
Returning Multiple Values

A Swift function is intended to return a single value, but what about instances in which we need to return multiple values? We can wrap them in a collection such as an array or a tuple. Although collections usually include numerous items, the collection as a whole is considered a single value, thus allowing for it to be returned from a function with no errors.

Imagine we’re creating a function that returns our favorite book’s name, author, and the year that it was published. We’d like to format and return its characteristics in tuple form. Here’s how we can set it up:

func favoriteBook() -> (name: String, author: String, yearPublished: Int) { return ("Harry Potter and the Philosopher's Stone", "J.K. Rowling", 1997) }

The favoriteBook() function does not accept any parameters but returns multiple values: name, author and yearPublished as a tuple. Within the return statement, parentheses are used to format the tuple and separate each item with a comma.

let book = favoriteBook() print(book) // Prints: (name: "Harry Potter and the Philosopher\'s Stone", author: "J.K. Rowling", yearPublished: 1997)

Calling the function above and printing the constant in which it is stored, we get a tuple output. We can then further interact with the tuple using dot syntax to access each value using its named parts:

print(book.name) // Prints: Harry Potter and the Philosopher's Stone print(book.author) // Prints: J.K. Rowling

Instructions

1.

In Cuisine.swift, set up a function, favoriteCuisine() that returns a tuple of your favorite cuisine.

favoriteCuisine() should not accept any parameters but must return the following named values in tuple form:

  • name of type String
  • dish of type String

Note: You will see an error in the terminal on the right, but it will go away in the next step when we populate the body of the function with code.

2.

Within the function’s body, return a tuple containing information about your favorite cuisine.

3.

Below the function declaration, invoke the function and store it in a constant, cuisine.

On the following line, use string interpolation and dot syntax within a print() statement to output the following message:

My favorite [cuisine name] dish is [cuisine dish]!

Folder Icon

Take this course for free

Already have an account?