Destructuring Tuples in Swift

In Swift, destructuring means pulling a tuple apart into multiple variables with a single assignment.

Here is how tuple destructuring syntax looks like:

var (val1, val2, val3) = threeValues

Where:

  • val1, val2, val3 are variables where the tuple values are stored.
  • threeValues is a tuple of three values.

For instance, let’s create a function that returns a tuple:

func getInfo() -> (name: String, email: String) {
     return (name: "Matt", email: "matt@example.com")
}

Now, here is one way to access the values of the tuple:

let info = getInfo()

print(info.name) // prints "Matt"
print(info.email) // prints "matt@example.com"

But you can do this with a single line by utilizing the tuple destructuring:

let (name, email) = getInfo()

print(name) // prints "Matt"
print(email) // prints "matt@example.com"

Next, let’s take a look at how to apply tuple destructuring to a classic programming interview question.

Swap Two Variables without a Third?

You can use tuple destructuring to swap two variables without a third helper variable:

var a = 1
var b = 2

(a, b) = (b, a) // Now b = 2 and a = 1

Thanks for reading.

Happy coding!

Further Reading

Swift – Upgrade Your Skills with These 8 Tips

iOS Development Tips in 2021

Share this article with others:

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email

Learn these 10 tips to write professional code.

 

Make your coding life easier with these amazing command-line tools

 

Learn how to use latest advancements in AI to write faster.

 

Leave a Comment

Your email address will not be published.