Swift – Destructuring syntax

Tram Ho


If you’ve ever coded javascript , you should be no stranger to destructuring syntax – a very elegant syntax for “box breaking” and removing values ​​from objects . Short, clean, nice, looks like this:

In Swift we have a similar syntax, but is used with tuples . Suppose there is a tuple like this:

If you want to get 3 values ​​in this tuple to assign to 3 variables in a normal way, you will write something like this:

But if using destructuring syntax, you just need to write:

Short and much cooler, right?

Destructuring in Swift is often used with three main purposes: Get values ​​out of tuples, assign values ​​to multiple variables at the same time, and swap values ​​with each other.

Get the value out of tuples

In the example above you have seen destructuring used for this purpose, but this technique will be especially useful when you are working with functions that return multiple values ​​at once . Take for example this function:

The above function returns both the name and the age. Often you will want to assign these 2 values ​​to 2 different variables for flexibility. If we don’t use destructuring, we have to type quite long:

As for destructuring, you just need to:

In case you don’t need to use a value, you can use the _ sign to ignore that value , like this:

Assign values ​​to multiple variables at the same time

Next, you can use this technique to assign values ​​to multiple variables at the same time. These values ​​can be hard fixes, or it can be the return value of a certain function:

Using this technique with closely related values , such as the coordinates on the map, is very beneficial for reading and understanding code.

Swap values ​​with each other

Assuming there are 2 variables Int, a and b, now how do you swap the values of these two variables together without using the third variable?

In most languages ​​you would do this:

As for Swift, you can use destructuring to do this:

Still only need a single line.

As you can see, using destructuring syntax not only saves you lines of code, but also makes your code easier to read, understand and look even cooler.

Hope my article will help you to have a useful tool when coding Swift

Share the news now

Source : Viblo