Destructuring Tuples in Swift

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

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

func getInfo() -> (name: String, email: String) {
     return (name: "Matt", email: "")

Now, this is one way for accessing the tuple (this is likely what you’ve seen and used before):

let info = getInfo()

print( // prints "Matt"
print( // prints ""

But did you know that you can also do it like this, by utilizing destructuring to tear the tuple apart into separate variables:

let (name, email) = getInfo()

print(name) // prints "Matt"
print(email) // prints ""

Cool, now you know what destructuring is. Next, let’s see how to apply it in solving one of the classic coding interview problems.

Swap Two Variables without a Third

This is a classic interview question that can be solved by applying what you just learned about destructuring tuples in Swift.

In Swift, 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

Pretty cool, right?

Thanks for reading. I hope you find it useful. Feel free to share this article if you think others can find it useful too!

You May Be Interested

Swift – Upgrade Your Skills with These 8 Tips

iOS Development Tips in 2021

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest

Leave a Comment

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