Return multiple values from a function in Swift

You can return multiple values from a function in Swift programming. But not in a generous way. It is a bit tricky to perform this task.

In order to return multiple values from a Swift function, we will use Tuple. We can send each value as a tuple element in the function and then return the tuple from the function.

func studentData() -> (Int, String, Double) {
    return (14, "Student", 49.8 )
}

print( studentData() )

If we call the function inside the print method like you can see above, we will be able to see the output given below:

(14, "Student", 49.8)

As you can see, the tuple is printed in the output.

It is possible also to get a specific value by providing the index number of the returned tuple element. In real-life iOS development projects, we have to perform this task often.

Complete code

Look at the code below:

func studentData() -> (Int, String, Double) {
    return (14, "Mohit Agarwal", 47.8 )
}

var student = studentData()

var age = student.0
var name = student.1
var weight = student.2

print(age)
print(name)
print(weight)

In the above code, we store each tuple element in variables. We have used the index number to get the elements from the returned tuple.

The naming of tuple element in the function definition

We can also give the name for the elements of the tuple at the time of defining the function. Giving names for tuple elements will increase the code readability and help other developers to crack the code.

Below is how we can do it:

func studentData() -> (age: Int, name: String, weight: Double) {
    return (14, "Mohit Agarwal", 47.8 )
}

See the complete code below:

func studentData() -> (age: Int, name: String, weight: Double) {
    return (14, "Mohit Agarwal", 47.8 )
}

var student = studentData()

var age = student.age
var name = student.name
var weight = student.weight

print(age)
print(name)
print(weight)

If you run the above piece of code, it will return the same output as you did it using the index number before. Using the name is more convenient instead of using the index number.

I hope, this tutorial will help you in the journey to becoming a developer or if you are already a developer, then I hope this tutorial will be helpful for you in your projects.

Leave a Reply

Your email address will not be published. Required fields are marked *