Swift: Returning Multiple Values

Returning Multiple Values in Swift:

Although a Swift function is a design to return a single value, what if we need to return multiple values? We can use a collection like an array or a tuple to wrap them. Despite the fact that collections typically contain many items, the collection as a whole is treated as a single value, allowing it to be returned from a function with no errors.

Assume we’re writing a function that returns the name, director, and released date of our favourite movie. We’d like to format and return its attributes as a tuple. This is how we can do it:

func movie() -> (name: String, director: String, releasedDate: Int) {
  return ("Jurassic Park", "Steven Spielberg", 1993);

The movie() function takes no arguments and returns a tuple with three values: name, director, and releasedDate. Parentheses are used within the return statement to format the tuple and to separate each item with a comma.

let favoriteMovie = movie();
// Prints: (name: "Jurassic Park", director: "Steven Spielberg", releasedDate: 1993)

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

print(favoriteMovie.name); // Prints: Jurassic Park
print(favoriteMovie.director); // Prints: Steven Spielberg

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: