Coding, Tech & Software Simplified

Destructuring Tuples in Swift

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

Here is what 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"

As another useful example, you can use tuple destructuring to pick values in a for loop.

For instance:

let list = [("Alice", 1), ("Bob", 2), ("Charlie", 3)]

for (name, position) in list {
    print("\(position): \(name)")
}

Output:

1: Alice
2: Bob
3: Charlie

If you have a tuple with a value you are not interested in, you can use the underscore operator as a discard variable.

For instance, given a list of tuples, where each tuple has a name and a number, we can ignore the number by destructuring it into the variable _:

let list = [("Alice", 1), ("Bob", 2), ("Charlie", 3)]

for (name, _) in list {
    print(name)
}

Output:

Alice
Bob
Charlie

To learn more about the underscore operator in Swift, feel free to check this article.

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

How to Swap Two Variables without a Third 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

This piece of code works such that:

  • On the left, you destructure a tuple into variables a and b
  • On the right, you create a tuple that stores the original variables in the reversed order.

Thanks for reading.

Happy coding!

Further Reading

Swift – Upgrade Your Skills with These 8 Tips

iOS Development Tips in 2021

Share

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